角度:将输入值重置为以前的值 [英] Angular: Reset input value to previous value

查看:28
本文介绍了角度:将输入值重置为以前的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Angular 2+ 中,是否可以通过编程将输入的值重置为其先前的值?

我有选择"下拉菜单,因此选择一个值时,如果某些验证失败,我需要将其值重置为前一个值.

如何使用 ngModel(模板表单)和 formControl(响应式表单)实现相同的效果?(只需要知道这两种方法是否可行).

我发现,如果我们将 ngModelChange 事件放在模板中 select 标签中的 ngModel 之前,那么在 ngModelChange 事件中,我们会在更改之前获得 ngModel 的值.参考:https://github.com/angular/angular/issues/11234>

但我认为这种方法并不简洁,有时可能会令人困惑.

解决方案

是的,可以使用响应式表单方法和 rxjs 运算符 成对.

使用 rxjs 运算符 pairwisestartWith

在组件中订阅 formControl valueChanges

示例代码:

this.myForm.controls['control1'].valueChanges.pipe(startWith(1), pairwise()).subscribe(([prevValue, selectedValue]) =>{控制台日志(上一个值);//前一个值控制台日志(selectedValue);//新值});}

您还可以检查工作 演示

注意:我正在使用 startWith 因为,当它成对时会发出值有两个值(prev 和 current).所以在startWith中添加默认值1(默认选项的值).

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.

解决方案

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.

这篇关于角度:将输入值重置为以前的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆