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?
change is bound to the HTML onchange event. It is a DOM event. ngModelChange is bound to the model variable binded to your input. No such class is required.
In Angular, We will use ngModel for two way data binding. Whenever a change happens in ngModel , Angular will trigger ngModelChange event. ngModelChange is the @output property of ngModel directive.
The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.
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 }
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.text
like so:
setTimeout(() => console.log(this.text), 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With