停止 Angular 中的无限循环反应式表单控制更新

Mol*_*och 4 rxjs angular angular-reactive-forms

我在表单上有 2 个输入,一个名为“ageMonths”的数字输入,以及一个名为“dateOfBirth”的日期选择器。

我希望用户能够输入年龄的月份,或使用日期选择器选择出生日期 (dob)。如果他们从日期选择器输入 dob,我希望月份字段更新为以月为单位的年龄。如果他们输入以月为单位的年龄,我希望日期选择器跳转到该日期。我正在使用反应形式。

我添加了一个类级别变量来保存一个切换,每次任一控件的值发生更改时都会读取并设置该切换。但这并没有按预期工作,我认为是由于事件没有按照我期望的顺序触发。

我需要做什么才能使这项工作成功?

我的代码是:

ignoreDateUpdate = false;
form: FormGroup;
...
constructor(...){
this.form = new FormGroup({
    dateOfBirth: new FormControl({ value: new Date()}),
    ageMonths: new FormControl({ value: 0 }),
    ...
});
...
this.form.get('ageMonths').valueChanges.subscribe(
m => {
    if (ignoreDateUpdates) {return};
    ignoreDateUpdates = true;
    <code to set DateSelectorValue>
    ignoreDateUpdates = false;
    });
this.form.get('dateOfBirth').valueChanges.subscribe(
dob => {
    if (ignoreDateUpdates) {return};
    ignoreDateUpdates = true;
    <code to set MonthsInput>
    ignoreDateUpdates = false;
});
}
Run Code Online (Sandbox Code Playgroud)

Mol*_*och 11

{emitEvent: false}我回答这个问题是因为我通过将选项添加到 setValue 调用中获得了所需的行为:

const calcDate = <calculate date from months value>;
this.form.get('dateOfBirth').setValue(calcDate, { emitEvent: false });
Run Code Online (Sandbox Code Playgroud)

但我仍然想知道为什么切换字段没有按预期工作,如果有人可以解释的话?

  • 这帮助我找到了与此相关的所需内容......特别是从对更新函数的返回调用中补充更新的数据。有时您需要在表单模型中获取新数据,但不希望它触发“valueChanges”,否则更新会循环。对我来说,使用 `this.formRef.form.patchValue(someObject, { emmitEvent: false })` 就是神奇的酱汁! (2认同)