Sub topic 14
Nested FormArrays
This chapter assumes you can build a FormArray of FormGroups, bind it with formArrayName and formGroupName, and add or remove entries with push and removeAt. It also assumes you know typed forms and NonNullableFormBuilder. Here you will put a FormArray inside a group that is itself inside another FormArray, and learn where that goes wrong.
When nesting is the right model
Nest arrays when the data is a list of items and each item owns a list of its own. Examples are a quiz with questions that each have several answers, an order with shipments that each contain lines, and a timetable with days that each have time slots.
If the inner list is the same for every outer item and never changes shape, a flat array of groups is simpler. Nest only when the user adds and removes inner entries independently for each outer entry.
The form is a tree. Every FormArray and FormGroup is a node. Controls are the leaves.
A complete example
The component below builds a quiz. Each question has a text and an answers array. A validator requires at least two answers per question. The minItems function is the same one you wrote for a single array, so it works at any level.
import { Component, inject } from '@angular/core';
import {
AbstractControl,
NonNullableFormBuilder,
ReactiveFormsModule,
ValidationErrors,
Validators,
} from '@angular/forms';
export function minItems(min: number) {
return (control: AbstractControl): ValidationErrors | null => {
const length = (control as { length?: number }).length ?? 0;
return length >= min ? null : { minItems: { required: min, actual: length } };
};
}
interface AnswerData {
label: string;
correct: boolean;
}
interface QuestionData {
text: string;
answers: AnswerData[];
}
@Component({
selector: 'app-quiz-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="questions">
@for (question of questions.controls; track question; let qi = $index) {
<fieldset [formGroupName]="qi">
<input formControlName="text" placeholder="Question" />
<div formArrayName="answers">
@for (answer of question.controls.answers.controls; track answer; let ai = $index) {
<div [formGroupName]="ai">
<input formControlName="label" placeholder="Answer" />
<input type="checkbox" formControlName="correct" />
<button type="button" (click)="removeAnswer(qi, ai)">Remove answer</button>
</div>
}
</div>
@if (question.controls.answers.hasError('minItems')) {
<p>Add at least 2 answers.</p>
}
<button type="button" (click)="addAnswer(qi)">Add answer</button>
<button type="button" (click)="removeQuestion(qi)">Remove question</button>
</fieldset>
}
</div>
<button type="button" (click)="addQuestion()">Add question</button>
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`,
})
export class QuizFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
questions: this.fb.array([this.createQuestion()]),
});
get questions() {
return this.form.controls.questions;
}
createAnswer(label = '', correct = false) {
return this.fb.group({
label: [label, Validators.required],
correct: [correct],
});
}
createQuestion(text = '', answers: AnswerData[] = [
{ label: '', correct: false },
{ label: '', correct: false },
]) {
return this.fb.group({
text: [text, Validators.required],
answers: this.fb.array(
answers.map((a) => this.createAnswer(a.label, a.correct)),
minItems(2),
),
});
}
addQuestion() {
this.questions.push(this.createQuestion());
}
removeQuestion(qi: number) {
this.questions.removeAt(qi);
}
addAnswer(qi: number) {
this.questions.at(qi).controls.answers.push(this.createAnswer());
}
removeAnswer(qi: number, ai: number) {
this.questions.at(qi).controls.answers.removeAt(ai);
}
setQuestions(data: QuestionData[]) {
this.questions.clear();
data.forEach((q) => this.questions.push(this.createQuestion(q.text, q.answers)));
}
submit() {
console.log(this.form.getRawValue());
}
}How the template binds each level
formArrayName and formGroupName resolve their names relative to the nearest parent directive. The outer formArrayName="questions" looks up questions on form. The [formGroupName]="qi" inside the loop looks up index qi in that array. The inner formArrayName="answers" then looks up answers on that question group, and [formGroupName]="ai" picks an answer.
Each directive must sit inside the element of its parent. Move the inner formArrayName outside the [formGroupName]="qi" element and Angular throws an error that it cannot find the control by name.
Typing and navigation
Because the builder is NonNullableFormBuilder, the types flow down the tree. this.questions.at(qi) is a typed FormGroup. .controls.answers is a typed FormArray of answer groups. A typo such as .controls.answer fails at compile time.
In the template, the loop variable question is already the typed group. Writing question.controls.answers.controls avoids a helper method that takes an index. With a method you would call this.questions.at(qi) again on every change detection pass. Direct access also keeps the template type-checked under strict templates.
Adding and removing at each level
An inner change affects only that inner array. addAnswer(0) pushes a group onto the first question's answers and leaves the second question alone.
Removing an outer entry discards its whole subtree, inner array included. The list shifts after removeAt, so the next render passes fresh $index values to the buttons. Do not cache an index in a field and reuse it later.
Each control can have only one parent. Do not push the same FormGroup instance into two arrays to copy a question. Build a new one with createQuestion. A shared instance gets one parent pointer, so changes and validity updates reach only one of the arrays.
Validation across levels
Errors stay on the node that produced them, but validity flows upward. If one answer's label is empty, then that answer group, the answers array, the question group, the questions array and finally form are all invalid. That is why [disabled]="form.invalid" on the submit button works with no extra code.
Errors do not flow upward. form.errors stays null when an inner array fails minItems. Read the error from the array that owns it, as the template does with question.controls.answers.hasError('minItems').
An empty array has no failing children, so it is valid unless it has its own validator. If a question must always have answers, the validator on answers is what enforces it.
push and removeAt call updateValueAndValidity on the array and its ancestors, so you do not call it yourself after those methods. If you change a validator later with setValidators, you do have to call it.
Populating nested data
patchValue and setValue on a FormArray do not create controls. They write only into positions that already exist. For nested arrays the problem repeats at every level, so you need to build the structure first. The setQuestions method above does this. clear() empties the outer array. Each record then goes through createQuestion, which builds the inner array from the record's own answers.
When the data has been rebuilt, form.value matches it. A mismatch usually means a level was filled with patchValue before its controls existed.
Reusing the factory methods for both new rows and loaded rows keeps validators and structure consistent. A second code path that builds rows by hand will drift out of sync with the first.
Reading the value
form.getRawValue() returns plain nested objects and arrays:
{
"questions": [
{
"text": "Capital of France?",
"answers": [
{ "label": "Paris", "correct": true },
{ "label": "Lyon", "correct": false }
]
}
]
}form.value has the same shape but leaves out any disabled control at any depth. If you disable an inner control, for example to lock a loaded answer, use getRawValue() when you need it in the output.
Rendering cost
Every control in the tree takes part in validity and value propagation, and each add or remove walks upward through its ancestors. A tree of a few hundred controls is fine. At thousands of controls, consider the following:
- Track by the control object, as the example does with
track questionandtrack answer. Angular then reuses DOM for rows that keep the same control and removes only the rows whose controls are gone. Tracking by index would reuse DOM for the wrong control after a removal. - Use
{ emitEvent: false }when you build many controls in a loop and nobody needs the intermediate events. Pass it toclear()andpush(), then callupdateValueAndValidity()once at the end.
Common mistakes
- Putting
formGroupNameandformArrayNamein the wrong nesting order in the template. - Filling nested arrays with
patchValuebefore building the controls. - Pushing the same control instance into two arrays.
- Looking for an inner array's error on
form.errors. - Using
valuewhere disabled controls must be included.
Exercise
A user removes the second question from the quiz and then clicks "Add answer" on what is now the second question. The answer appears on the wrong question. The component stores the clicked question index in a field currentQuestion when the question first renders and uses it in addAnswer() with no argument. What is the cause, and how do you fix it?
Show answer
After removeAt, the questions after the removed one shift down by one index, but the cached currentQuestion field still holds the old index, so this.questions.at(currentQuestion) points at a different group. Fix it by passing the current $index from the template on each click, as in (click)="addAnswer(qi)". You can also pass the question's FormGroup itself and push onto question.controls.answers, which does not depend on any index.