代码之家  ›  专栏  ›  技术社区  ›  serlingpa

角度:将两个表单控件绑定到同一模型

  •  0
  • serlingpa  · 技术社区  · 5 年前

    我使用创建了两个控件 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,这会导致堆栈异常,但对它们有效。不幸的是,它的效率不如它所能达到的那么高,因为当两个输入中的任何一个发生变化时,这段代码会运行十几次或更多次。

    我如何才能做到这一点,使代码只执行必要的次数?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Ashish Ranjan    5 年前

    通过 emitEvent 期权虚假

    EmitEvent:无论是否提供(默认值),当控件值更新时,statusChanges和valueChanges可观察到的都会以最新状态和值发出事件。如果为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})
      }
    });