【问题标题】:Patching values in FormBuilder form and watching for changes causes infinite loop在 FormBuilder 表单中修补值并监视更改会导致无限循环
【发布时间】:2023-04-09 21:35:02
【问题描述】:

我有带有 3 个字段的简单 Angular FormBuilder 表单(在 Ionic 2 应用程序中):

constructor(public navCtrl: NavController, public navParams: NavParams,
    public viewCtrl: ViewController, private builder: FormBuilder) {
        this.form = this.builder.group({
            startDate: ['', Validators.required],
            endDate: ['', Validators.required],
            count: [0, Validators.required], //diff in days
        });
}

我的模板:

  <ion-item>
    <ion-label floating>Start</ion-label>
    <ion-datetime formControlName="startDate" [min]="today_iso" displayFormat="DD/MM/YYYY" pickerFormat="DD/MM/YYYY">
    </ion-datetime>
  </ion-item>

  <ion-item>
    <ion-label floating>End</ion-label>
    <ion-datetime formControlName="endDate" [min]="today_iso" displayFormat="DD/MM/YYYY" pickerFormat="DD/MM/YYYY">
    </ion-datetime>
  </ion-item>

  <ion-item>
    <ion-label fixed>Count</ion-label>
    <ion-input type="number" formControlName="count" ></ion-input>
  </ion-item>

我想使用 moment.js 动态计算两个日期之间的差异,然后修改 count 字段的表单值:

this.form.valueChanges.subscribe(data => {
  let startDate = moment(data.startDate);
  let endDate = moment(data.endDate);
  let diff = endDate.diff(startDate, 'days');

  if(diff>0) {
    this.form.patchValue({
      count: diff
    })
  }
});

但是,form.patchValue 似乎导致 valueChanges.subscribe 的另一次执行,我得到无限循环执行(超过最大调用堆栈大小)。我怎样才能避免这种情况?有没有更好的方法来动态修改表单值?

【问题讨论】:

    标签: javascript angularjs angular typescript ionic2


    【解决方案1】:

    我猜你正在寻找这个:

    this.form.patchValue({ count: diff }, { emitEvent: false });
    

    这样valueChange 不会被解雇

    Plunker Example

    【讨论】:

    • 如果我这样做,我认为我的模板不会更新为新的计数值。
    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2016-05-01
    • 2011-08-23
    • 2019-03-29
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多