Angular 2 ngModelChange old value

2019-01-26 06:13发布

问题:

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>

回答1:

This might work

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

or

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


回答2:

Example with input field...

<div *ngFor="let value of values">{{value}}
    <input [(ngModel)]="value" (focus)="old=value" (ngModelchange)="doSomething(old, value)">
</div>

doSomething(oldVal, newVal) {
    // some code
}