ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

我正在尝试创建一个包含此类型表单的表单:

formGroup

formControl

formControl

formArray

formGroup

formControl

formControl

当我点击按钮添加反应字段并在填写后提交表单时,第一个字段不包含任何数据。 我得到这个错误:

ERROR Error: Cannot find control with path: 'emails -> 0 -> email'

ERROR Error: Cannot find control with path: 'emails -> 0 -> send'

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent{


  profileForm = this.fb.group({
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
    }),
    emails: this.fb.array([''])
  });


  get emails() {
    return this.profileForm.get('emails') as FormArray;
  }

  addEmail() {
    this.emails.push(this.fb.group({
      email:[''],
      send:['']
    }));
  }

  constructor(private fb: FormBuilder){}

  public submit():void{
    console.log(this.profileForm.value);
  }


}

app.component.html

<form [formGroup]="profileForm" (ngSubmit)="submit()">

  <div>
    <label>firstName</label>
    <input type="text" formControlName="firstName">
  </div>

  <div>
    <label>lastName</label>
    <input formControlName="lastName" type="text">
  </div>

  <div formGroupName="address">
    <label>Adresse</label>
    <label>street</label><input formControlName="street" type="text">
    <label>city</label><input formControlName="city" type="text">
    <label>state</label><input formControlName="state" type="text">
  </div>

  <div formArrayName="emails">
    <h2>Aliases</h2>
    <button type="button" (click)="addEmail()">+ Add another alias</button>

    <div [formGroupName]="i" *ngFor="let e of emails.controls; let i=index;">
      <div>
        <label>email:</label>
        <input type="text" formControlName="email">
        <input type="checkbox" formControlName="send">

      </div>


    </div>
  </div>

  <button type="submit" [disabled]="!profileForm.valid">Submit</button>
</form>

使用

emails: this.fb.array([])

而不是

emails: this.fb.array([''])

Sample Demo on StackBlitz


参考

Creating an in-place editable table using FormArray