Sub topic 7
Repeating groups of fields
This chapter assumes you know TypeScript, Angular standalone components and templates, and the basics of FormControl, FormGroup and Validators. It also assumes you have seen FormArray of plain controls, formArrayName and push/removeAt. Here you apply them to the most common real-world case: a list where each row has several fields, such as order lines, phone numbers with a type, or education history.
Why an array of groups
A FormArray of plain FormControls fits a list of single values, such as email addresses. Most lists need more than one value per row. An order line has a name and a quantity, and a contact has a label and a number.
Put a FormGroup in each slot of the array. The array manages the list: its length, order, and which rows exist. Each group manages the fields of one row. Validity bubbles up, so one invalid field in one row makes its group invalid, then the array invalid, then the whole form invalid.
A factory function for one row
Every new row must be a new FormGroup instance. Write a single function that builds a row, and use it for the initial row, the Add button, and later when loading data.
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, Validators.required],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}The default arguments let you create an empty row with createItem() or a pre-filled row with createItem('Pen', 3). Because this is the only place that defines a row's shape, adding a field later means changing one function.
The full component
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-order-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" placeholder="Name" />
<input type="number" formControlName="quantity" />
<button type="button" (click)="removeItem(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="addItem()">Add item</button>
<button type="submit" [disabled]="form.invalid">Submit</button>
</form>
`,
})
export class OrderFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
get items() {
return this.form.controls.items;
}
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, Validators.required],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}
addItem() {
this.items.push(this.createItem());
}
removeItem(index: number) {
this.items.removeAt(index);
}
submit() {
console.log(this.form.getRawValue());
}
}How the binding resolves
The template uses three directives that work as a chain. Each one looks up its control relative to its parent directive.
[formGroup]="form"sets the root group.formArrayName="items"looks upform.get('items'). It must be aFormArray.[formGroupName]="i"looks upitems.at(i). Inside an array, the "name" of a child is its numeric index, so you bind it with brackets to pass a number rather than the string"i".formControlName="name"looks upnameinside that row's group.
Because each level resolves from its parent, the same template markup works for every row. Only the index changes.
The get items() accessor keeps the template short and gives you the typed FormArray without casting. With a NonNullableFormBuilder, this.form.controls.items is already typed as a FormArray of the row group type.
Adding, removing and reordering rows
push and removeAt cover the basic cases. Because each row is a standalone object, moving a row is a matter of removing it and inserting the same object elsewhere:
moveUp(index: number) {
if (index === 0) return;
const row = this.items.at(index);
this.items.removeAt(index);
this.items.insert(index - 1, row);
}This keeps the row's values, validation state, and touched/dirty flags, because you reinsert the same instance rather than creating a copy. With track item (tracking by control object), Angular also moves the existing DOM elements instead of rebuilding them, so focus and cursor position inside the row survive.
Each of these calls recalculates the array's value and validity and emits valueChanges. If you add many rows at once, such as when loading data, pass { emitEvent: false } to each push and call items.updateValueAndValidity() once at the end.
Reading the value
form.value for this form has the shape { items: [{ name, quantity }, ...] }. The array's value is a plain array with one object per row, in order. That maps directly onto a JSON request body.
value leaves out disabled controls, and disabled rows are omitted from the array output entirely if the whole group is disabled. getRawValue() includes everything. Use getRawValue() when you disable fields, for example a read-only price, but still want to submit them.
Validation across levels
Validators attach at three levels, and each level answers a different question.
| Level | Example | Question it answers |
|---|---|---|
| Control | `Validators.min(1)` on `quantity` | Is this field acceptable? |
| Row group | A validator checking `name` and `quantity` together | Is this row consistent? |
| Array | `minItems(1)` | Is the list acceptable as a whole? |
An array-level rule, such as a required minimum number of rows, is passed as the second argument to fb.array:
import { AbstractControl, FormArray, ValidationErrors } from '@angular/forms';
export function minItems(min: number) {
return (control: AbstractControl): ValidationErrors | null => {
const length = (control as FormArray).length;
return length >= min ? null : { minItems: { required: min, actual: length } };
};
}
// Usage: this.fb.array([this.createItem()], minItems(1))Without this validator, a user can remove every row and still submit a valid, empty form. To show the error, check items.hasError('minItems') in the template. To show a field error for one row, read it from that row's controls, for example item.controls.name.touched && item.controls.name.invalid inside the @for block.
Common problems
- Pushing the same group twice. Calling
push(group)twice with one variable puts one object in two slots. Editing one row edits both. Always callcreateItem()for each push. Cannot find control with path: 'items -> 0'. The template hasformGroupNamewithout a matchingformArrayNameancestor, orformArrayNamepoints to a control that is not aFormArray.formGroupName="i"without brackets. This passes the literal string"i". Use[formGroupName]="i".- Calling
patchValueto add rows.patchValueandsetValuefill existing controls only. They do not create missing rows. To load data, clear the array and push one new group per record, as in the next chapters. - Reading
form.valuewith disabled fields. Missing keys in the output usually mean a disabled control. UsegetRawValue().
Exercise
A user clicks "Add item" twice and types "Pen" in the second row, but "Pen" also appears in the first row. The addItem method is this.items.push(this.row), where this.row is a class field holding one FormGroup. What is wrong, and how do you fix it?
Show answer
Both slots in the array hold the same FormGroup instance, so both rows are bound to the same controls. Create a new group on each call: change addItem to this.items.push(this.createItem()), where createItem builds a fresh group with this.fb.group(...).
Exercise
You want the form to be invalid when the user has removed every row. Which level do you attach the validator to, and how do you show the message in the template?
Show answer
Attach it to the FormArray, as the second argument of fb.array, for example this.fb.array([this.createItem()], minItems(1)). In the template, show the message when items.hasError('minItems') is true.