我在 @Input
参数中传递了一个 formControl,该参数绑定(bind)到最大值应为 10 的数字类型的输入。
当用户键入更大的数字时,不应更改输入值。
阻止事件传播或获取旧值并重新设置它的方法是什么?
我尝试了 stack 和 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
最佳答案
经过一年多的经验,我认为我找到了最佳解决方案。要解决这个问题,最好的方法可能是使用 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);
}
})
}
关于valueChanges 上的 Angular 7 FormControl 获得旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473087/