Angular 7 FormControl on valueChanges获取旧值

时间:2018-11-25 23:36:25

标签: angular angular-reactive-forms angular7

我在@Input参数中传递了一个formControl,该参数绑定到最大值应为10的数字类型的输入。  当用户键入较大的数字时,不应更改输入值。

如何防止事件传播或获取旧值并重新设置?

我尝试了来自堆栈和github的许多其他解决方案,但是没有什么能解决我的问题。

 valuecontrol: FormControl = new FormControl(0);

  constructor(){
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue=>{
      if(newValue >= 10){
        // set previous value
        const oldValue = this.control.value;
        console.log("old value = ", oldValue)
        this.control.patchValue(oldValue);
      }
    })
  }.

演示:https://stackblitz.com/edit/angular-6ocjfj?file=src/app/app.component.ts

3 个答案:

答案 0 :(得分:16)

经过一年的经验,我认为我找到了一个最佳解决方案。要解决此问题,最好的方法可能是使用pairwise rxjs operator

感谢您能够获得流的先前值。

提供的代码段不能解决原始问题,因为它需要一些额外的步骤,但是可以解决“如何获取旧值?” 上的原始问题。

代码如下:

control: FormControl = new FormControl(0);

  constructor(){
    this.control.valueChanges.pipe(
      distinctUntilChanged(),
      pairwise() // gets a pair of old and new value
    ).subscribe(([oldValue, newValue])=>{
      console.log(oldValue, newValue)
      if(newValue >= 10){
        // set previous value
        this.control.patchValue(oldValue);
      }
    })
  }

生活代码:https://stackblitz.com/edit/angular-tfrstg

答案 1 :(得分:2)

将新值更新为FormControl值后,将触发valueChanges事件,这就是为什么您无法获得旧值的原因。

最好的方法是使用@JB Nizet提到的验证器。

如果您想继续使用解决方案,则可以利用Angular的ngDoCheck生命周期挂钩来保留旧的价值。

修改后的代码:

export class AppComponent implements DoCheck {
  private oldValue;
  control: FormControl = new FormControl(0);

  constructor() {
    this.control.valueChanges.pipe(distinctUntilChanged()).subscribe(newValue => {
      if (newValue >= 10) {
        // set previous value
        console.log("old value = ", this.oldValue)
        this.control.patchValue(this.oldValue);
      }
    })


  }
  ngDoCheck() {
    this.oldValue = this.control.value
  }
}


StackBlitz

答案 2 :(得分:0)

在输入控件上将[max]属性设置为10

<input type="number" [max]="10" [formControl]="control">

这样,您可以完全删除newValue >= 10条件。

相关问题