Angular 2 ngModelChange old value

Can someone please tell me what is the best practice for comparing the old and new ngModel value?

In angular 1:

$scope.$watch('someProperty', funciton(oldVal, newVal){ // code goes here }) 

I ask about this because (ngModelChange) never brings me oldVal , only newVal .

In my case, I use ngModel in the <select> and compare the old selection with the new one:

 <select [(ngModel)]="current" (ngModelChange)="onModelChange($event)"> <option *ngFor="let item of myArray" [ngValue]="item">{{item.name}} </option> </select> 
+12
source share
3 answers

It can work

 (ngModelChange)="onModelChange(oldVal, $event); oldVal = $event;" 

or

 (ngModelChange)="onModelChange($event)" 
 oldValue:string; onModelChange(event) { if(this.oldValue != event) { ... } this.oldValue = event; } 
+14
source

Input field example ...

 <div *ngFor="let value of values">{{value}} <input [(ngModel)]="value" (focus)="old=value" (ngModelchange)="doSomething(old, value)"> </div> doSomething(oldVal, newVal) { // some code } 
+5
source

Just for the future

we should note that [(ngModel)] = "hero.name" is just the shortest path that can be removed from scratch: [ngModel] = "hero.name" (ngModelChange) = "hero.name = $ event".

So if we remove the code from sugar, we get:

<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

or

<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

If you inspect the above code, you will notice that in the end we have 2 ngModelChange events that must be executed in some order.

To summarize : if you put ngModelChange before ngModel, you will get the $ event as a new value, but your model object will still have the previous value. If you put it after ngModel, the model will already have a new value.

SOURCE

0
source

Source: https://habr.com/ru/post/1013900/


All Articles