我在一个表单上有 2 个输入,一个名为“ageMonths”的数字输入和一个名为“dateOfBirth”的日期选择器。
我希望用户能够输入年龄的月份,或使用日期选择器选择出生日期 (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;
});
}
最佳答案
我正在回答这个问题,因为我通过将 {emitEvent: false}
选项添加到我的 setValue 调用中来获得所需的行为:
const calcDate = <calculate date from months value>;
this.form.get('dateOfBirth').setValue(calcDate, { emitEvent: false });
但是如果有人能解释一下,我仍然想知道为什么切换字段没有按预期工作?
关于angular - 停止 Angular 中的无限循环 react 形式控制更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55645248/