Angular FormArray - 无法读取 属性 'push' 的 null

Angular FormArray - Cannot read property 'push' of null

我正在使用 Angular Reactive FormArray 在添加按钮上添加多个输入。

我的设置中有多个 formGroup。当我尝试 add/push 输入时,出现“无法读取 属性 'push' of null”的错误。

是我的 formGroup 设置有问题还是因为 formArray 中有多个 FormGroups

我的代码:Html

<form [formGroup]="form">
    <input type="checkbox" formControlName="published"> Published
    <div *ngIf="form.controls.published.value">

    <h2>Credentials</h2>
    <button (click)="addCreds()">Add</button>

    <div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value; let i = index">
        <ng-container [formGroupName]="i">
        <input placeholder="Username" formControlName="username">
        <input placeholder="Password" formControlName="password">
        </ng-container>
    </div>

    </div>
</form>

Angular代码:

form: FormGroup;

constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      published: true,
      formArray: this.fb.array([
        this.fb.group({
          credentials: this.fb.array([]),
        })
      ])
    });
}

addCreds() {
    const creds = this.form.get('credentials') as FormArray;
    creds.push(this.fb.group({
      username: '',
      password: '',
    }));
}

我也有https://stackblitz.com/edit/angular-form-array-example-hfmrm2

由于您嵌套了 formArray,因此必须按如下方式更改模板。

component.html

 <ng-container
      formArrayName="formArray"
      *ngFor="let forArr of form.get('formArray').controls; let x = index"
    >
      <ng-container [formGroupName]="x">
        <div
          formArrayName="credentials"
          *ngFor="
            let creds of forArr.controls.credentials?.controls;
            let i = index
          "
        >
          <ng-container [formGroupName]="i">
            <input placeholder="Username" formControlName="username" />
            <input placeholder="Password" formControlName="password" />
          </ng-container>
        </div>
      </ng-container>
    </ng-container>

component.ts

 addCreds() {
    const formArray = this.form.get("formArray") as FormArray;
    (formArray.controls[0].get("credentials") as FormArray).push(
      this.fb.group({
        username: "",
        password: ""
      })
    );
  }

Forked Example