Angular2 NgModelChange Previous Value


Answer :

What you can do is,

DEMO : http://plnkr.co/edit/RXJ4D0YJrgebzYcEiaSR?p=preview

<input type="text"         [ngModel]="text"                      //<<<###changed [(ngModel)]="text" to [ngModel]="text"        (ngModelChange)="textChanged($event)">   private textChanged(event) {             console.log('changed', this.text, event);     this.text=event;                          //<<<###added  } 

So found kinda weird(at least for me) possible solution for this with least changes in the code in question. So on assigning the (ngModelChange) attribute before [(ngModel)] what I get is following with the same handler:

changed *older value* *new value* 

I get the new value in this.textlike so:

setTimeout(() => console.log(this.text), 0); 

all you need to do is to put (ngModelChange)="textChanged($event)" to the left of [(ngModel)] element in the html tag, like:

<input (whatever...) (ngModelChange)="textChanged($event)" [(ngModel)]="text"> 

This way, inside textChanged(event), the element you are binding to still has the previous value, while event is the new one

If you type

<input (whatever...) [(ngModel)]="text" (ngModelChange)="textChanged($event)"> 

The event will be called with new value only. However:

<input (whatever...) (ngModelChange)="textChanged($event)" [(ngModel)]="text" (ngModelChange)="textChanged($event)">   -  

Will get you both events with previous and current value


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools