如何在 Angular2/4 FormArray 字段中动态设置值?

How to dynamically set values in Angular2/4 FormArray fields?

我得到了一个可以向其中添加行的动态 table。如何在 col 3 中动态设置数据?我正在使用表单构建器来创建我的表单,并且有一个方法可以接受在 table 中动态插入行。当我在 col1 中写东西时,我订阅更改并计算两个 cols 的总和以将其放在第三个 col.

    public sumRow() {
        this.myForm
          .get('rows')
          .valueChanges
          .subscribe((val) => {

             // latest edit
             val.foreach((item) => {
                item.col3 = item.col1 + col2;
                // But this one does not fill the col3 but 
                // it already giving the correct values
             });

             //loop to the val instead 

             // const ctrl = this.myForm.controls['rows'];
             // ctrl.controls.forEach((field) => {
             // const col1 = parseInt(field.get('col1').value, 10);
             // const col2 = parseInt(field.get('col2').value, 10);
             // const sum = col1 + col2;
             // How to set these values to col3?
             // Doesn't work: field.get('col3').setValue(sum);
        });
    }

  public createForm() {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
    });
  }

  public pushRowItems(items) {
    this.myForm.addControl('rows', this.fb.array([items]));
  }

  public initItemRows() {
    return this.fb.group({
      col1: 0,
      col2: 0,
      col3: 0,
    });
  }

  public ngOnInit() {
    this.createForm();
    this.pushRowItems(this.initRowItems());
    this.sumRow();
  }

我将你上面的代码添加到我的项目中,除了一个小改动外,它工作得很好......我不得不将 ctrl 转换为 FormArray:

    const ctrl = <FormArray>this.customerForm.controls['addresses'];
    ctrl.controls.forEach((field) => {
      const col1 = parseInt(field.get('street1').value, 10);
      const col2 = parseInt(field.get('street2').value, 10);
      const sum = col1 + col2;
      // How to set these values to col3?
      field.get('city').setValue(sum);
    });

(我的示例使用了地址,所以我只是将数字填入地址字段以进行尝试。)

当您说它对您不起作用时...您是不是遇到了错误?如果是这样,错误是什么?

你可以在这里找到我使用的代码:https://github.com/DeborahK/Angular2-ReactiveForms/tree/master/Demo-Final-Updated

我刚刚将上述更改添加到 populateTestData 方法并且它按预期工作......

我会做的是跳过 valueChanges 并使用 ngModel 的单向绑定作为列的总和。不知道你的模板是什么样子的,你有几个选择:

将禁用的输入字段显示为第三列,或者然后使用隐藏的输入字段并改为显示 <p>

如果使用禁用字段,则需要使用getRawValue()获取禁用字段的值。

通常我不建议将 ngModel 与响应式形式一起使用,但在这种情况下没问题,因为我们不使用它将它绑定到 TS 中的单独变量。

下面是您的代码使用隐藏选项后的样子:

<table formArrayName="rows">
  <tr *ngFor="let item of myForm.controls.rows.controls; let i = index" [formGroupName]="i">
    <td><input type="number" formControlName="col1"></td>
    <td><input type="number" formControlName="col2"></td>
    <td> <input type="number" hidden formControlName="col3" [ngModel]="item.controls.col1.value + item.controls.col2.value"></td>
    <td><p>{{item.controls.col3.value}}</p></td>
  </tr>
</table>

StackBlitz