bula
bula

Reputation: 9419

ngModel and change method on input does not work

I have the following HTML template

<input type="text" [(ngModel)]="mobile" (change)="mobileChanged()">

Here is my .ts

mobileChanged = () => {
    console.log(this.mobile);
};

Is it wrong to have ngModel and change in the same element? In my case mobileChanged is not being called while I type in the input. How ever, when I check the value of mobile, it is updated correctly.

This is Angular 7.

Upvotes: 1

Views: 1835

Answers (2)

Dino
Dino

Reputation: 8292

Using change will trigger the mobileChanged() when you lose the focus of the input field (ex: Click outside the field). If you want to trigger mobileChanged() while typing, use (ngModelChange)="mobileChanged($event)" instead.

Upvotes: 9

Joffrey K
Joffrey K

Reputation: 234

I sugest to read this tutorial : https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html in order to understand well the two-way Data Binding and to master the use of ngModel.

As it's explained using ngModel bind an expression to the element’s input event, so it's similar to :

<input [value]="mobile" (input)="mobile = $event.target.value">

you could manage the update of the value and your log in the same method called.

Upvotes: 0

Related Questions