Sub topic 12
Repeating Fields with FormArray
Some forms need a field, or a group of fields, that repeats a number of times the user decides: order line items, phone numbers, or the guests on a booking. FormGroup won't fit here because its keys are fixed names. A FormArray is a form control container whose children are indexed by position, like a JavaScript array. Each child is itself a control, so a child can be a FormControl, a FormGroup, or another FormArray.
This chapter assumes you can already create typed FormControl and FormGroup instances, bind them with formGroup and formControlName, use NonNullableFormBuilder, and nest groups inside groups.
How a FormArray Fits the Form Tree
A FormArray sits in the form tree like any other control. Its value is an array of its children's values. Its status is aggregated from its children: if any child is invalid, the array is invalid, and so is every ancestor above it.
For this tree, form.value has the shape { items: [{ sku, qty }, { sku, qty }] }.
Typing the Array
With strict typing, every child of a FormArray has the same type. You declare that type with the generic parameter FormArray<T>. A type alias for the row keeps the signatures readable:
import { FormArray, FormControl, FormGroup } from '@angular/forms';
export type LineItemForm = FormGroup<{
sku: FormControl<string>;
qty: FormControl<number>;
}>;
export type OrderForm = FormGroup<{
items: FormArray<LineItemForm>;
}>;You rarely write these types by hand when you use FormBuilder, because fb.array([...]) infers them. They are still worth declaring when a function builds or receives rows, or when you start the array empty. An empty fb.array([]) cannot infer its element type, so annotate it explicitly.
A Complete Line-Item Form
The component below lets the user add, remove, and reorder rows. It also loads saved data and enforces at least one row.
import { Component, inject } from '@angular/core';
import { FormArray, FormControl, FormGroup, NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
type LineItemForm = FormGroup<{
sku: FormControl<string>;
qty: FormControl<number>;
}>;
interface LineItem {
sku: string;
qty: number;
}
@Component({
selector: 'app-order-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="sku" placeholder="SKU" />
<input type="number" formControlName="qty" />
<button type="button" (click)="moveUp(i)" [disabled]="i === 0">Up</button>
<button type="button" (click)="removeItem(i)" [disabled]="items.length === 1">Remove</button>
@if (item.controls.qty.touched && item.controls.qty.hasError('min')) {
<span>Quantity must be at least 1.</span>
}
</div>
}
</div>
@if (items.hasError('minlength')) {
<p>Add at least one item.</p>
}
<button type="button" (click)="addItem()">Add item</button>
<button type="submit" [disabled]="form.invalid">Place order</button>
</form>
`,
})
export class OrderFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array<LineItemForm>([this.createItem()], Validators.minLength(1)),
});
get items(): FormArray<LineItemForm> {
return this.form.controls.items;
}
createItem(item: LineItem = { sku: '', qty: 1 }): LineItemForm {
return this.fb.group({
sku: [item.sku, Validators.required],
qty: [item.qty, [Validators.required, Validators.min(1)]],
});
}
addItem(): void {
this.items.push(this.createItem());
}
removeItem(index: number): void {
this.items.removeAt(index);
}
moveUp(index: number): void {
const row = this.items.at(index);
this.items.removeAt(index, { emitEvent: false });
this.items.insert(index - 1, row);
}
loadItems(saved: LineItem[]): void {
this.items.clear({ emitEvent: false });
saved.forEach((item) => this.items.push(this.createItem(item), { emitEvent: false }));
this.items.updateValueAndValidity();
}
onSubmit(): void {
const order: { items: LineItem[] } = this.form.getRawValue();
console.log(order);
}
}How the template binding resolves
The directives resolve names relative to their parent. formArrayName="items" looks up items in the enclosing formGroup. Inside it, [formGroupName]="i" takes a number, not a string, and looks up the child at that index. formControlName="sku" then resolves inside that row group. The square brackets on [formGroupName] matter. Without them, Angular passes the literal string "i".
For a FormArray of plain FormControls, such as a list of tags, skip the inner group and bind each input with [formControlName]="i".
The FormArray API
| Method or property | What it does |
|---|---|
| `at(i)` | Returns the child control at index `i` |
| `push(control)` | Appends a control to the end |
| `insert(i, control)` | Inserts a control at index `i` |
| `removeAt(i)` | Removes the control at index `i` |
| `setControl(i, control)` | Replaces the control at index `i` |
| `clear()` | Removes every control |
| `length` | Number of children |
| `controls` | The underlying array of child controls |
Every mutating method takes an optional { emitEvent: false }. Use it when you make many changes in a row, then call updateValueAndValidity() once at the end. Otherwise each push fires valueChanges and reruns validation up the tree.
Common Errors and Edge Cases
patchValue and setValue do not add or remove rows
setValue and patchValue only write values into controls that already exist. If you patch an array of three items into an array that has one row, patchValue silently drops the extra two. setValue throws instead, because it requires an exact match. To load server data, rebuild the rows as loadItems does: clear the array, then push one control per item.
Tracking rows in @for
The track expression tells Angular which DOM element belongs to which row. track $index works for a list that only grows at the end. When you remove or reorder rows, though, index tracking reuses the DOM nodes by position. Focus, text selection, and any component state inside a row can end up attached to the wrong row. Each child control is a stable object, so track item follows the row itself, and that is the safer default.
Validators on the array
Validators attached to the FormArray see the whole array value. Validators.minLength(n) and Validators.maxLength(n) work on it because they check the value's length. The error key is lowercase (minlength). An array error makes the parent form invalid even when every row is valid, so display it next to the array, as the template does.
Indexes are not identities
After a removeAt, every later row's index shifts down by one. Don't store indexes for later use, for example in a pending HTTP callback. Keep a reference to the control instead, and look up its current position with items.controls.indexOf(control) when you need it.
Exercise
A user edits an order with one row, and your code calls this.form.patchValue({ items: [{ sku: 'A', qty: 2 }, { sku: 'B', qty: 5 }] }). What does the form contain afterward, and how should you load this data instead?
Show answer
The form still has one row, set to sku 'A' and qty 2. patchValue only writes to existing controls, so the second item is ignored. Instead, call items.clear(), push createItem(item) for each saved item (optionally with { emitEvent: false }), then call updateValueAndValidity() once.
Exercise
Your row template uses track $index. A user types into the SKU field of row 3 and then deletes row 2, and their cursor jumps to a different row. Why does this happen, and what is the fix?
Show answer
With index tracking, Angular keeps DOM nodes by position. Removing row 2 makes Angular reuse the old row-3 node for the item now at index 2 and destroy the last node, so the focused element no longer belongs to the row the user was editing. Track the control object instead (track item). Each row's DOM then stays attached to its own FormGroup.
Exercise
Write the declaration for a FormArray of non-nullable string controls named tags that starts empty and allows at most five tags, using NonNullableFormBuilder fb.
Show answer
tags: this.fb.array<FormControl<string>>([], Validators.maxLength(5)). The explicit generic is needed because an empty array cannot infer its element type. Add a tag with this.form.controls.tags.push(this.fb.control('')) and bind each input with [formControlName]="i" inside formArrayName="tags".