无法将嵌套表单组绑定到反应形式中的表单数组?

时间:2019-12-18 14:48:13

标签: angular angular-reactive-forms

https://stackblitz.com/edit/angular-reactive-forms-eg-s1v5zs?file=src/app/app.component.html

  

无法将{form control}绑定到数据[     {       “ group1”:“”,       “ group2”:{         “数据”:“”       }     }   ]

     
    

需要使用表单控件名称进行绑定

  

 <form [formGroup]="formGroup">
    <div formArrayName="features">
        <div class="row no-gutters form-group" *ngFor="let feature of features.controls; let i = index; let last = last"
            [formGroupName]="i">
            Grp:1 <input
        type="text"
        class="form-control px-2 col"
        formControlName="group1"
        title="feature"
        >
            <!-- //How to bind  value of data in html??? -->
            <div [formGroup]="group2">
                <input type="text"
                class="form-control px-2 col"
                formControlName="group2"
                title="feature"
                >
            </div>
            <button class="col btn btn-success" (click)="addFeature()">
                +
                </button>
        </div>
    </div>
    <pre>
    {{ features.value|json}}
  </pre>
</form>

typeScript
  constructor(private fb: FormBuilder) {
    this.addFeature();
  }
  formGroup = this.fb.group({
    features: this.fb.array([])
  });
  get features(): FormArray {
    return this.formGroup.get("features") as FormArray;
  }
  addFeature(): void {
    let data = this.fb.group({
      group1: new FormControl("grp_1"),
      group2: this.fb.group({
        data: new FormControl("grp_2")
      })
    });
    this.features.push(data);
  }`enter code here`

2 个答案:

答案 0 :(得分:1)

您的文字formControlName="group2"上有<input>。相反,您应该将data表单组的group2控件绑定到输入formControlName="data"

答案 1 :(得分:0)

如果要使用对象数组创建嵌套表单,则应使用FormGrop。

尝试一下:

addFeature(): void {
    let data = this.fb.group({
      group1: new FormControl("grp_1"),
      group2: this.fb.group({
        data: new FormControl("grp_2")
      }),
      group3: this.fb.array([
        this.fb.group({
          data: new FormControl("grp_3")
        })
      ])
    });
    this.features.push(data);
  }

Forked Example