问题
In Angular 2+, is it possible to reset value of an input to its previous value programmatically?
I have 'Select' dropdown, whereupon selecting a value I need to reset its value to the previous one, if certain validation fails.
How can I achieve the same using ngModel (Template form) and formControl (Reactive Form)? (Just need to know if its possible by both the approaches).
I have figured out that if we place the ngModelChange event before the ngModel in the select tag in the template, the in the ngModelChange event we get value of ngModel prior to the change. Reference: https://github.com/angular/angular/issues/11234
But I think this approach is not concise and might be confusing at times.
回答1:
Yes, it is possible using Reactive forms approach and with rxjs operator pairwise.
Subscribe to formControl valueChanges
in your component with rxjs operators pairwise
and startWith
Sample code :
this.myForm.controls['control1'].valueChanges
.pipe(startWith(1), pairwise()).subscribe(
([prevValue, selectedValue]) => {
console.log(prevValue); // previous value
console.log(selectedValue); // new value
}
);
}
You can also check the working DEMO
Note : I am using startWith because, pairwise will emit values when it has two values (prev and current). So add default value 1
(value of default option) in startWith
.
来源:https://stackoverflow.com/questions/54390556/angular-reset-input-value-to-previous-value