Sub topic 11
Repeating Fields with FormArray
This chapter assumes you already know how to build a FormGroup, bind it with formGroup and formControlName, and create controls with NonNullableFormBuilder. You also need to be comfortable with the @for block in templates.
Why FormArray Exists
A FormGroup has a fixed set of named keys. Some data, such as order line items, phone numbers, or tags, has a length the user decides at runtime. A FormArray is a control container that holds an ordered list of controls, accessed by index instead of by name. It aggregates value and validity just like a group. Its value is an array, and it is invalid if any child is invalid.
Building and Binding an Array of Groups
The component below starts with one line item and lets the user add and remove more.
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-order-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div formArrayName="items">
@for (item of items.controls; track $index) {
<div [formGroupName]="$index">
<input formControlName="sku" placeholder="SKU" />
<input type="number" formControlName="qty" />
<button type="button" (click)="removeItem($index)">Remove</button>
</div>
}
</div>
<button type="button" (click)="addItem()">Add item</button>
</form>
`,
})
export class OrderFormComponent {
private fb = inject(FormBuilder).nonNullable;
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
get items() {
return this.form.controls.items;
}
createItem() {
return this.fb.group({
sku: ['', Validators.required],
qty: [1, [Validators.required, Validators.min(1)]],
});
}
addItem(): void {
this.items.push(this.createItem());
}
removeItem(index: number): void {
this.items.removeAt(index);
}
}Three directives connect the template to the model:
| Directive | Binds to | Lookup key |
|---|---|---|
| `formArrayName="items"` | The `FormArray` | Name in the parent group |
| `[formGroupName]="$index"` | One child group | Numeric index in the array |
| `formControlName="sku"` | A leaf control | Name in the child group |
formGroupName uses a property binding because the index is a number expression, not a string literal.
The Factory Method Pattern
createItem() returns a fresh group every time it is called. Put every row's construction in one factory like this. If you reuse the same control instance in two places, both rows share state. Because the array is typed, push accepts only groups with the same shape, so a mismatched row is a compile error.
Common Errors
- Iterating
itemsinstead ofitems.controls.FormArrayis not iterable. Loop over itscontrolsarray. - Missing
formArrayNamewrapper. Without it,[formGroupName]="0"looks for a key0on the root group and throws "Cannot find control". - Untyped getter. Writing
this.form.get('items') as FormArraythrows away the element type. Preferthis.form.controls.items. - Resetting to fewer rows.
reset()andpatchValue()never add or remove controls. To replace the rows, callclear()and then push new groups.
Exercise
The order form has three line items and you call form.patchValue({ items: [{ sku: 'A', qty: 2 }] }). How many items does the array contain afterward, and what are their values?
Show answer
It still contains three items. patchValue only updates matching indices, so item 0 becomes { sku: 'A', qty: 2 } and items 1 and 2 keep their current values. To end up with exactly one item, call items.clear(), push one group from createItem(), and then patch it.
Exercise
Write a method hasValidItems() that returns true only when the array holds at least one item and every item is valid.
Show answer
hasValidItems(): boolean { return this.items.length > 0 && this.items.valid; }. The array's valid flag is already false if any child group is invalid, so you only need to add the length check.