Angular4: unexpected app refresh with @ViewChild()

1k views Asked by At

I'm trying to get the value of an input field via @ViewChild(). However, even though it seems to work, this method triggered unexpected refresh into the app:

-app refreshes right after clicking the button trigerring the event

-app refreshes once when navigating through the app whith a navbar

template:

<input type="text" id="name" class="form-control" #nameInput>
<button class="btn btn-success" type="submit" (click)="addShop()">Add</button>
<p>{{shopName}}</p>

component.ts:

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {
@ViewChild('nameInput') shopName:ElementRef;
@ViewChild('amountInput') shopAmount:ElementRef;

coucou:string;


addShop(){
    this.shopName = this.shopName.nativeElement.value;
}

  constructor() { }

  ngOnInit() {
  }
}
2

There are 2 answers

0
Pankaj Parkar On BEST ANSWER

When button type is submit inside a form, on form submit event it tries to hit action(attribute) provided on form level. If there is no action attribute on form, it refreshes the page. To stop this behaviour you could change button type to button(just by removing type attribute wouldn't fix issue, implicitly button has submit type).

<button class="btn btn-success" type="button" (click)="addShop()">Add</button>

In angular world you should be using (ngSumbit)="submit()" event on form level then you can keep your button type as submit. Behind the scene form event gets suppressed by ngSubmit event. You can make ajax call from your function specified on ngSubmit event.

Markup

<form (ngSubmit)="addShop()" #heroForm="ngForm">
  <input type="text" id="name" class="form-control">
  <button class="btn btn-success" type="submit">Add</button>
  <p>{{shopName}}</p> 
</form>
0
The One On

Remove type="submit" in the button, just replace it for type="button"

Change the following line:

<button class="btn btn-success" type="submit" (click)="addShop()">Add</button>

to:

<button class="btn btn-success" type="button" (click)="addShop()">Add</button>

The browser thinks you're submitting a form, that's why it refreshes the page