角度:将输入值重置为上一个值 [英] Angular: Reset input value to previous value
问题描述
在Angular 2+中,是否可以通过编程将输入值重置为其先前值?
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.
如何使用ngModel(模板形式)和formControl(反应形式)实现相同目的? (只需知道两种方法是否可行).
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).
我已经发现,如果将ngModelChange事件放置在模板中的select标签中的ngModel之前,则在ngModelChange事件中,我们会在更改之前获得ngModel的值. 参考: https://github.com/angular/angular/issues/11234
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.
推荐答案
Yes, it is possible using Reactive forms approach and with rxjs operator pairwise.
使用rxjs运算符pairwise
和startWith
Subscribe to formControl valueChanges
in your component with rxjs operators pairwise
and startWith
示例代码:
this.myForm.controls['control1'].valueChanges
.pipe(startWith(1), pairwise()).subscribe(
([prevValue, selectedValue]) => {
console.log(prevValue); // previous value
console.log(selectedValue); // new value
}
);
}
您还可以检查有效的演示
注意:我正在使用 startWith ,因为成对会在以下情况下发出值它有两个值(上一个和当前).因此,请在startWith
中添加默认值1
(默认选项的值).
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
.
这篇关于角度:将输入值重置为上一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!