Angular2 ngModelChange previous value

柔情痞子 提交于 2019-12-18 11:03:34

问题


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?


回答1:


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 
}



回答2:


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);



回答3:


all you need to do is to put (ngModelChange)="textChanged($event)" to the left of [(ngModel)] element in the html tag, like:

<input (whatever...) (ngModelChange)="textChanged($event)" [(ngModel)]="text">

This way, inside textChanged(event), the element you are binding to still has the previous value, while event is the new one




回答4:


<input (ngModelChange)="preTextChanged($event)" [(ngModel)]="text" (ngModelChange)="postTestChanged($event)">

In this way you can know the previous value and the next value



来源:https://stackoverflow.com/questions/40172351/angular2-ngmodelchange-previous-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!