反应式窗体 更新 ArrayForm 时的角度中断



我在 Angular 应用程序中使用响应式表单时遇到问题。 我设法在 Plunkr 中隔离了问题。

https://plnkr.co/edit/KiTHcaaZZA6kwDI0sfeR?p=preview

我有一个带有 ArrayForm 部分的表单,我可以在其中使用按钮添加行。 这些行中的每一行都有许多输入字段,其中一些显示其他字段的结果。 例如,在我的 plunkr 中,我有一个 MAX 和一个 MIN 按钮,它们是数字,当它们都有一个值时,我需要更新另一个字段的值,称为 TOTAL。

所以这是 html 模板:

<form [formGroup]="form">
<div>
<input type="text" formControlName="client" placeholder="client">
</div>
<button type="button" (click)="addPublisher()">Add Publisher</button>
<div formArrayName="publishers">
<div *ngFor="let item of publishers; let i = index;">
<div [formGroupName]="i">
<input type="number" formControlName="max" placeholder="max">
<input type="number" formControlName="min" placeholder="min">
<input type="text" formControlName="total" placeholder="total">
</div>
</div>
</div>
</form>

这才是最重要的。我订阅了发布者中的更改,并且仅在更改不是要添加或删除的行时才更新行。

ngOnInit() {
(this.form.get('publishers') as FormArray).valueChanges
.map((publishers: any[]) => {
if (this.totalPublishers === publishers.length) {
publishers.forEach((publisher, index) => {
console.log(`update publishers ${index}`);
this.updatePublisher((this.form.get('publishers') as FormArray).get([index]) as FormGroup);
});
} else {
console.log(`update total from ${this.totalPublishers} to ${publishers.length}`);
this.totalPublishers = publishers.length;
}
})
.subscribe();
}

为了更新值,我这样做

private updatePublisher(publisher: FormGroup) {
this.updateTotals(publisher);
}
private updateTotals(publisher: FormGroup) {
const max = publisher.get('max').value;
const min = publisher.get('min').value;
if (max && min) {
console.log(max, min);
const total = max - min;
publisher.get('total').setValue(total);
}
}

如果我执行此操作,当我更新第一个字段(max)时,它会检查值,并且由于 min 尚不存在,因此没有任何反应。正确。 然后,当我编辑第二个值(min)时,此updateTotals将执行无数次,总计在最后计算并在字段中更新,但是如果我尝试再次编辑这些字段并更新值,则没有任何反应。

知道为什么会这样吗?

谢谢。

当您调用setValuevalueChange事件时,将在updateValueAndValidity内触发。一个选项应该可以帮助您

publisher.get('total').setValue(total, { emitEvent: false });

这样,您的valueChange处理程序就不会无限期执行。

固定普伦克

最新更新