我使用ControlValueAccessor
界面创建了两个控件- 一个日期选择器和一个年龄选择器 - 并希望使用相同的值将它们绑定在一起。这些代表退休日期和年龄,用户应该能够修改一个并查看另一个输入更新。
我通过订阅form.valueChanges
observable来做到这一点,就像这样:
this.form.valueChanges.subscribe((val) => {
if (val.retirementDate !== this.currentDatePickerValue) {
// retirement date changed
this.currentDatePickerValue = val.retirementDate;
setTimeout(() => this.retirementAgeCtrl.setValue(this.currentDatePickerValue));
} else if (val.retirementAge !== this.currentAgePickerValue) {
// retirement age changed
this.currentAgePickerValue = val.retirementAge;
setTimeout(() => this.retirementDateCtrl.setValue(this.currentAgePickerValue));
}
});
没有setTimeout()
s,这会导致堆栈异常,但有了它们就可以了。不幸的是,它的效率不如预期,因为当任一输入更改时,此代码会运行十几次或更多次。
我怎样才能做到这一点,以便代码只根据需要执行多少次?
将emitEvent选项传递为false
发射事件:当为真或不提供时(默认值),statusChanges 和 valueChanges observables 都会在控件值更新时发出具有最新状态和值的事件。如果为 false,则不发出任何事件。
this.form.valueChanges.subscribe((val) => {
if (val.retirementDate !== this.currentDatePickerValue) {
// retirement date changed
this.currentDatePickerValue = val.retirementDate;
this.retirementAgeCtrl.setValue(this.currentDatePickerValue, {emitEvent: false})
} else if (val.retirementAge !== this.currentAgePickerValue) {
// retirement age changed
this.currentAgePickerValue = val.retirementAge;
this.retirementDateCtrl.setValue(this.currentAgePickerValue, {emitEvent: false})
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句