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() {
}
}
When button type is submit inside a
form
, on formsubmit
event it tries to hitaction
(attribute) provided on form level. If there is no action attribute onform
, it refreshes the page. To stop this behaviour you could change buttontype
tobutton
(just by removingtype
attribute wouldn't fix issue, implicitly button hassubmit
type).In angular world you should be using
(ngSumbit)="submit()"
event onform
level then you can keep your button type assubmit
. Behind the scene form event gets suppressed byngSubmit
event. You can make ajax call from your function specified onngSubmit
event.Markup