我有一个formbuilder组,正在使用valueChanges监听更改并触发保存功能,然后在表单上刷新功能:
this.ticketForm.valueChanges.debounceTime(1000).distinctUntilChanged()
.subscribe(data => {
this.saveTicket();
this.refreshTicket();
})
然后我重新加载表单并使用patchValue将数据重新分配到表单字段(以及页面上的其他位置,特别是更改日志),例如:
this.ticketForm.patchValue(ticket, { emitEvent: false });
然而,尽管emitEvent:false,这会导致表单的无限循环保存。
这是一个Angular 4 / Ionic 3错误还是我的误解?
答案 0 :(得分:7)
尝试通过以下方式将onlySelf: true
与emitEvent: false
一起添加:
this.ticketForm.patchValue(ticket, {emitEvent: false, onlySelf: true});
答案 1 :(得分:1)
作为一种解决方法,我将跳过添加到rxjs管道
this.form.valueChanges
.pipe(skip(1)).subscribe();
答案 2 :(得分:1)
在使用 Angular 9.1.13 时,我遇到了同样的问题。
尝试使用 FormControl.setValue
和 FormGroup.patchValue
API,并在所有可能的组合中使用建议的参数 {emitEvent: false, onlySelf: true}
。
valueChanges
observable 仍在被触发。
最终唯一对我有用的是:
myForm.disable();
myForm.patchValue({myControl: ''}, {onlySelf: true, emitEvent: false});
myForm.enable();
答案 3 :(得分:0)
由于代表无法发表评论,因此我将其发布为@Craig Wayne的答案。
emitEvent:false仅在您使用以下方法监听表单控件上的值更改时起作用:
this.form.valueChanges.controlName.subscribe(val => doSomething(val));
如果绑定到模型,则在元素事件上发出更改,而无论如何:
<input (ngModelChange)="doSomething($event)"/>
答案 4 :(得分:0)
this.filter_form.valueChanges
.pipe(debounceTime(400), startWith(this.filter_form.value), pairwise(), takeUntil(this._OnDestroy))
.subscribe(([prev, curr]) => {
console.log(prev, curr)
if(prev.date != curr.date && curr.date == 'select_date'){
this.filter_form.patchValue({
this.filter_form.get('from_date').setValue(moment().startOf('month').toDate(), {emitEvent: false});
this.filter_form.get('to_date').setValue(moment().add('5','M').endOf('month').toDate(), {emitEvent: false});
}, {emitEvent: false});
this.getLeave();
}
});
我删除了 debounceTime(400) 并使用 setValue 修补单个控件值
它对我有用
答案 5 :(得分:0)
为什么在值改变时使用 patchValue 而不是在初始化时设置一次?
就我个人而言,在两个必需的 FormControl 之间构建选项时,我在不同的上下文中遇到了这个问题
我有一个字段正在清除另一个字段(按照设计,只应填写一个),但随后订阅触发了原始字段的清除。发射事件:假没有帮助,因为我需要我的验证器在更新时运行。添加 if(value) 有助于避免级联修补。见下文:
this.formGroup.controls.item1.valueChanges.subscribe(value => {
if(value){
this.formGroup.patchValue({
'item2':null
})
}
})
this.formGroup.controls.item2.valueChanges.subscribe(value => {
if(value){
this.formGroup.patchValue({
'item1':null
})
}
})
注意:为了简单起见,我没有包含 .pipe(takeUnitl(this.destroy$))。如果你不包括这个,它就会有内存泄漏