Sub topic 14
Nested FormArrays
This chapter assumes you can build a FormArray of FormGroups, bind it with formArrayName and formGroupName, and read typed values. A nested FormArray is a FormArray that sits inside a group, and that group is itself an entry of an outer FormArray. Use it when a repeated row owns its own repeated list. Examples are team members who each have several phone numbers, or order lines that each have several tags.
The shape of the data
The form below has one outer array, members. Each member is a group with a name control and an inner array, phones.
Building it
Put the inner array inside the factory method that creates a member. Every new member then gets its own phones array.
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-team-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="members">
@for (member of members.controls; track member; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" placeholder="Name" />
<div formArrayName="phones">
@for (phone of phones(i).controls; track phone; let j = $index) {
<input [formControlName]="j" placeholder="Phone" />
<button type="button" (click)="removePhone(i, j)">Remove phone</button>
}
</div>
<button type="button" (click)="addPhone(i)">Add phone</button>
<button type="button" (click)="removeMember(i)">Remove member</button>
</div>
}
</div>
<button type="button" (click)="addMember()">Add member</button>
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`,
})
export class TeamFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
members: this.fb.array([this.createMember()]),
});
get members() {
return this.form.controls.members;
}
phones(memberIndex: number) {
return this.members.at(memberIndex).controls.phones;
}
createMember(name = '', phones: string[] = ['']) {
return this.fb.group({
name: [name, Validators.required],
phones: this.fb.array(phones.map((p) => this.fb.control(p, Validators.required))),
});
}
addMember() {
this.members.push(this.createMember());
}
removeMember(index: number) {
this.members.removeAt(index);
}
addPhone(memberIndex: number) {
this.phones(memberIndex).push(this.fb.control('', Validators.required));
}
removePhone(memberIndex: number, phoneIndex: number) {
this.phones(memberIndex).removeAt(phoneIndex);
}
submit() {
console.log(this.form.getRawValue());
}
}How the binding nests
Each directive resolves its name against the nearest parent container.
formArrayName="members"findsmembersinform.[formGroupName]="i"selects entryiofmembers.formArrayName="phones"findsphonesinside that member group.[formControlName]="j"selects entryjofphones.
Do not repeat the outer path. If the inner formArrayName is placed outside the member's formGroupName element, Angular looks for phones on the wrong group and throws an error.
Typing and helper methods
Because the builder is non-nullable, TypeScript infers the type FormArray<FormGroup<{ name: FormControl<string>; phones: FormArray<FormControl<string>> }>>. The phones(i) helper therefore returns a typed array, and the template needs no casts. Keep one helper per level. Calling this.members.at(i).controls.phones inline in several places makes the code hard to read.
Populating from data
Reuse the same factory for loading, as you did for flat arrays. Clear the outer array and push one member per record.
setMembers(data: { name: string; phones: string[] }[]) {
this.members.clear();
data.forEach((d) => this.members.push(this.createMember(d.name, d.phones)));
}patchValue does not create missing controls at either level, so a member with more phones than the form currently has would lose the extra values.
Common errors
- Wrong index in a handler.
removePhone(i, j)needs both indexes. Passing onlyjremoves a phone from the wrong member. - Shared inner array. Creating the
phonesarray once and reusing it in every member gives all members the same controls. Build it insidecreateMember. - Too many levels. Past two levels, the template and the helpers become hard to follow. Consider extracting the inner list into a child component that receives the inner
FormArrayas an input.
Exercise
You add a "Remove phone" button for each phone. Which two values must the click handler receive, and how do you reach the right control to remove?
Show answer
It needs the member index i and the phone index j. Call this.members.at(i).controls.phones.removeAt(j), or use the helper this.phones(i).removeAt(j).