Angular 7 FormControl on valueChanges获取旧值

kar*_*luS 5 angular angular-reactive-forms angular7

我收到了一个传给formControl的@Input参数,该参数绑定到最大值应该为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);
      }
    })
  }.
Run Code Online (Sandbox Code Playgroud)

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

kar*_*luS 21

经过一年多的经验,我想我找到了一个最佳解决方案。要解决这个问题,最好的方法可能是使用pairwise rxjs 运算符

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

提供的代码段没有解决原始问题,因为它需要一些额外的步骤,但它解决了关于“如何获取旧值?”的原始问题。.

代码来了:

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);
      }
    })
  }
Run Code Online (Sandbox Code Playgroud)

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

  • 我遇到的问题是,如果您更改值但不发出事件,则从成对 obs 发出的“先前”值不再正确。我正在尝试监听更改,检查条件,请求确认,如果未确认则恢复。问题是我需要旧值和新值来检查条件,并且在恢复后无法发出事件。 (2认同)