Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 ngModelChange previous value

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?

like image 331
irtaza Avatar asked Oct 21 '16 08:10

irtaza


People also ask

What is the difference between change vs ngModelChange?

change is bound to the HTML onchange event. It is a DOM event. ngModelChange is bound to the model variable binded to your input. No such class is required.

What triggers ngModelChange?

In Angular, We will use ngModel for two way data binding. Whenever a change happens in ngModel , Angular will trigger ngModelChange event. ngModelChange is the @output property of ngModel directive.

What does [( ngModel )] mean?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.


2 Answers

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  } 
like image 50
Nikhil Shah Avatar answered Sep 17 '22 09:09

Nikhil Shah


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); 
like image 31
irtaza Avatar answered Sep 20 '22 09:09

irtaza