Search code examples
angularangular-ngmodelangular2-forms

Angular 2 ngModelChange old value


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>

Solution

  • This might work

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

    or

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