1

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.

Dino
  • 7,779
  • 12
  • 46
  • 85
bula
  • 8,719
  • 5
  • 27
  • 44

2 Answers2

9

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.

Dino
  • 7,779
  • 12
  • 46
  • 85
0

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.

Joffrey K
  • 185
  • 9