我使用创建了两个控件
ControlValueAccessor
接口-日期选择器和年龄选择器-希望使用相同的值将它们绑定在一起。这些代表退休日期和年龄,用户应该能够修改其中一个,并看到另一个输入更新。
我通过订阅
form.valueChanges
可观察,如:
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,这会导致堆栈异常,但对它们有效。不幸的是,它的效率不如它所能达到的那么高,因为当两个输入中的任何一个发生变化时,这段代码会运行十几次或更多次。
我如何才能做到这一点,使代码只执行必要的次数?