繁体   English   中英

更新ArrayForm时反应形式Angular断开

[英]Reactive form Angular breaks when updating an 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尚不存在,因此不会发生任何事情。 正确。 然后,当我编辑第二个值(最小值)时,此updateTotals执行了无数次,最后计算了总数,并在字段中进行了更新,但是如果我尝试再次编辑这些字段并更新值,则什么也不会发生。

知道为什么会这样吗?

谢谢。

调用setValue将在updateValueAndValidity触发valueChange事件。 一种选择应该可以帮助您

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

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

固定柱塞

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM