patchValue with { emitEvent: false, onlySelf: true } trigger



我有一个重置按钮,它使用patchValue重置域的值

onReset() {      
this.addModelForm.patchValue({ domain: '', emitEvent: false, onlySelf: true}); 
}

这是域的值更改方法:

this.addModelForm.get('domain').valueChanges.subscribe(domainId => {
console.log("value changed!")
});

它在控制台上打印"值已更改!我不想触发 valueChanges 方法。发出事件不起作用。

对我有用的是这样的结构,它在单元测试中也运行良好。

programmaticUpdate = false; // prevents excessive event emission and infinite loops
// ...
private suppressEvents(callback: () => void) {
this.programmaticUpdate = true;
try {
callback();
} finally {
this.programmaticUpdate = false;
}
}

用法:

this.suppressEvents(() => {
this.addModelForm.patchValue({ domain: '' }); 
});

不要忘记忽略这样的程序化valueChanges

this.addModelForm.get('domain').valueChanges.pipe(
filter(() => !this.programmaticUpdate), // ignore programmatic updates
takeUntil(this.destroy$), // best practice, read about it online
).subscribe(domainId => {
console.log("value changed!")
});

emitEvent从来没有为我工作过,即使在今天使用 Angular 15。

资料来源:6年的Angular经验。

由于您在 FormGroup 上使用 patchValue 它应该是这样的:

试试这个:

this.addModelForm.patchValue( { domain: '' },{emitEvent: false}); 

最新更新