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
Since you have nested formArray you have to change the template as follows.
component.html
component.ts
Forked Example