Angular2 ngModelChange previous value

irtaza picture irtaza · Oct 21, 2016 · Viewed 34.3k times · Source

Is there a way to get the previous(last) value of a field on ngModelChange? What I have goes something like this

HTML

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

Handler

private textChanged(event) {
    console.log('changed', this.text, event);
}

What I get is

changed *newvalue* *newvalue*

Of course I can keep the older value using another variable, but is there a better way?

Answer

micronyks picture micronyks · Oct 21, 2016

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 
}