Angular 2 ngModelChange old value

Ron Avraham picture Ron Avraham · Jan 9, 2017 · Viewed 26.5k times · Source

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

In angular 1:

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

I am asking this because (ngModelChange) never brings me the oldVal , only the newVal.

In my case, I am using ngModel in a <select> tag 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>

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jan 9, 2017

This might work

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

or

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