Angular: Reset input value to previous value

不想你离开。 提交于 2019-12-11 08:40:01

问题


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

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