如何修复=> FormArray。找不到路径控制

时间:2019-09-02 04:37:10

标签: angular angular-forms angular8

我正在尝试使用反应性表单和formArray创建一些表单,但是我正在尝试并且出现此错误“ FormArray。找不到带有路径的控件”

我需要绑定这些字段并更新数组,以便稍后发送回api。

我尝试更改名称,即formcontrolname,formcontrol,formArrayName。

builder.Services.AddLogging();

  ngOnInit() {
    this.formGroundUse = this.fb.group({
      published: true,
      groundUses: this.fb.array([])
    });

    this.dataModel = Object.create(null);
    const groudUse = this.formGroundUse.controls.groundUses as FormArray;


    this.tableData.forEach((item, index) => {
      groudUse.push(
        this.fb.group({
          title: new FormControl(item.title),
          value: new FormControl(item.value),
          percentage: new FormControl(item.percentage)
        })
      );

      console.log(groudUse);
    });

  this.formGroundUse.valueChanges
      .subscribe(data => {
        this.dataModel = data;
        console.log('listening');
      });
}

我需要将这些字段绑定到ts上以创建一些计算,但是我只是在dataModel中得到了旧值。

1 个答案:

答案 0 :(得分:0)

您给定的htmlts有一些不匹配。无需在文本框value中使用formControl就可以了。您可以参考下面的示例。

HTML

<form [formGroup]="formGroundUse">
  <ng-container *ngFor="let data of formGroundUse.controls['groundUses']?.controls; let i = index" formArrayName="groundUses">
    <ng-container [formGroupName]="i">
      <tr>
        <td class="table-subtitle">{{data.title}}</td>
        <td class="input-container">
          <label for="">Área (Ha)</label>
          <input type="text" class="form-input" formControlName="value">
        </td>
        <td>{{data.percentage}}</td>
      </tr>
    </ng-container>
  </ng-container>
</form>

<pre>
  {{formGroundUse.value | json}}
</pre>

TS

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'ngrxstore';
  dataModel = {};
  formGroundUse: FormGroup;
  tableData = [
    {
      title: 'Title 1',
      value: 'Value 1',
      percentage: 99.10
    }, {
      title: 'Title 2',
      value: 'Value 2',
      percentage: 90.00
    }
  ];
  constructor(public fb: FormBuilder) {

  }

  ngOnInit(): void {
    this.formGroundUse = this.fb.group({
      published: true,
      groundUses: this.fb.array([])
    });
    const groudUse = this.formGroundUse.controls.groundUses as FormArray;
    this.tableData.forEach((item, index) => {
      groudUse.push(
        this.fb.group({
          title: new FormControl(item.title),
          value: new FormControl(item.value),
          percentage: new FormControl(item.percentage)
        })
      );
    });
  }
}