Angular FormArray - Cannot read property 'push' of null

3.8k Views Asked by At

Im working with Angular Reactive FormArray to add multiple inputs on add button.

I have multiple formGroup in my setup. I get Error of "Cannot read property 'push' of null" when I try to add/push input.

Is it anything wrong with my formGroup setup or Is it because of Multiple FormGroups in formArray

My Code: 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 Code:

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: '',
    }));
}

I also have https://stackblitz.com/edit/angular-form-array-example-hfmrm2

1

There are 1 best solutions below

5
On BEST ANSWER

Since you have nested formArray you have to change the template as follows.

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