Sub topic 14
Model repeated fields with arrays
This chapter assumes you can read the Signal Forms basics from earlier chapters. That means creating a form with form(), binding inputs with [field], reading field state as signals, and writing a schema function. It also assumes you know signal() and update(). Signal Forms is experimental in Angular 21, so names such as Field may change in later releases.
Why arrays need their own treatment
Many forms contain a list of similar things: order line items, phone numbers, team members. The number of rows is not known at build time, and each row needs the same rules.
Signal Forms handles this without a separate array class. The model is a plain signal holding an array, and the form mirrors the model's shape. Two consequences follow:
- To add or remove a row, you change the model. The form follows.
- To validate every row the same way, you declare the rules once with
applyEach().
The model
Start with a model type. Each row gets an id so the template can track rows when they are added or removed.
interface LineItem {
id: number;
description: string;
quantity: number;
}
interface Order {
customer: string;
items: LineItem[];
}The initial value contains one empty row, so the form never starts with a blank list.
const initial: Order = {
customer: '',
items: [{ id: 1, description: '', quantity: 1 }],
};Validate every row with applyEach()
applyEach(path.items, fn) calls fn once for the item shape and applies the rules to every row. This is true whether the row exists now or is added later. The callback receives a path for one item. You use it like the path in a normal schema function.
const orderForm = form(this.model, (path) => {
required(path.customer, { message: 'Customer is required' });
applyEach(path.items, (item) => {
required(item.description, { message: 'Describe the item' });
min(item.quantity, 1, { message: 'Quantity must be at least 1' });
});
});The callback runs against a path, not against a particular row. So item.description here means "the description of whichever row this is".
Arrays are validated as a whole too
You can also attach a rule to the array field itself. This suits constraints on the list, such as "at least one row".
validate(path.items, ({ value }) =>
value().length > 0
? null
: { kind: 'no-items', message: 'Add at least one item' }
);Rules on the array and rules on its rows are independent. The parent form is valid only when both are satisfied.
Render the rows
Each field in the array is itself a field, and you can iterate over the array field in the template. Inside the loop, item.description and item.quantity are child fields you can bind.
@for (item of orderForm.items; track item().value().id; let i = $index) {
<fieldset>
<legend>Item {{ i + 1 }}</legend>
<label>Description <input [field]="item.description" /></label>
@if (item.description().touched() && item.description().invalid()) {
@for (error of item.description().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
<label>Quantity <input type="number" [field]="item.quantity" /></label>
<button type="button" (click)="removeItem(item().value().id)">Remove</button>
</fieldset>
}The track expression matters. Tracking by id lets Angular keep the DOM for surviving rows when a row in the middle is removed. Tracking by $index would reuse the wrong DOM for the rows after the removed one. Typed text and focus can then end up on the wrong row.
Add and remove rows by updating the model
You never call an add method on the form. You write a new array into the model signal.
protected addItem() {
this.model.update((m) => ({
...m,
items: [...m.items, { id: this.nextId++, description: '', quantity: 1 }],
}));
}
protected removeItem(id: number) {
this.model.update((m) => ({
...m,
items: m.items.filter((item) => item.id !== id),
}));
}Always produce a new array. Calling m.items.push(...) mutates the array in place, and signals only notify when the value they hold is replaced.
The complete component
This example combines every piece. It runs as shown in a project that has Angular 21 and @angular/forms/signals.
import { Component, signal } from '@angular/core';
import {
form,
Field,
required,
min,
validate,
applyEach,
submit,
} from '@angular/forms/signals';
interface LineItem {
id: number;
description: string;
quantity: number;
}
interface Order {
customer: string;
items: LineItem[];
}
@Component({
selector: 'app-order',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>Customer <input [field]="orderForm.customer" /></label>
@for (item of orderForm.items; track item().value().id; let i = $index) {
<fieldset>
<legend>Item {{ i + 1 }}</legend>
<label>Description <input [field]="item.description" /></label>
@if (item.description().touched() && item.description().invalid()) {
@for (error of item.description().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
<label>Quantity <input type="number" [field]="item.quantity" /></label>
<button type="button" (click)="removeItem(item().value().id)">Remove</button>
</fieldset>
}
@for (error of orderForm.items().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
<button type="button" (click)="addItem()">Add item</button>
<button type="submit" [disabled]="orderForm().invalid()">Place order</button>
</form>
`,
})
export class OrderComponent {
private nextId = 2;
private readonly model = signal<Order>({
customer: '',
items: [{ id: 1, description: '', quantity: 1 }],
});
protected readonly orderForm = form(this.model, (path) => {
required(path.customer, { message: 'Customer is required' });
validate(path.items, ({ value }) =>
value().length > 0
? null
: { kind: 'no-items', message: 'Add at least one item' }
);
applyEach(path.items, (item) => {
required(item.description, { message: 'Describe the item' });
min(item.quantity, 1, { message: 'Quantity must be at least 1' });
});
});
protected addItem() {
this.model.update((m) => ({
...m,
items: [...m.items, { id: this.nextId++, description: '', quantity: 1 }],
}));
}
protected removeItem(id: number) {
this.model.update((m) => ({
...m,
items: m.items.filter((item) => item.id !== id),
}));
}
protected async onSubmit(event: Event) {
event.preventDefault();
await submit(this.orderForm, async (f) => {
console.log(f().value());
return undefined;
});
}
}How state rolls up
Each row has its own valid, touched, and dirty signals. The parent field combines them. If one row's description is empty, orderForm().invalid() is true and the submit button is disabled. If you only need to know whether one row is wrong, read item().invalid() inside the loop.
Edge cases and common errors
- Mutating instead of replacing.
push()andsplice()on the model array do not notify the signal. Create a new array with spread,filter, ormap. - Tracking by index. Removing a middle row shifts DOM state onto the wrong row. Give each row a stable
id. - Reusing an id. If you compute
idfromitems.length, removing a row then adding one can create a duplicate. Use a counter that only increases, asnextIddoes above. - Empty list.
applyEachrules never run when there are no rows. A rule such as "at least one" belongs on the array field. - Number inputs. With
type="number"the model should hold anumber. If the model starts with'', the type and the input disagree. Start with1or0. - Replacing the whole array. If you reset with fresh objects, rows get new identities and their touched and dirty state resets with them. That is usually what you want after a successful submit, but not after an unrelated update.
Exercise
A user fills in rows 1, 2, and 3, then removes row 2. Row 3's text appears in the wrong place and its focus jumps. The template uses @for (item of orderForm.items; track $index). What is wrong, and what is the fix?
Show answer
Tracking by $index tells Angular that the row at position 1 is the same row as before. After the removal, the old row-3 DOM element is dropped and the row-2 element is reused for the data of old row 3. The DOM state, such as focus and cursor position, no longer matches the data. Add a stable id to each model item and use track item().value().id. Generate ids from a counter that never decreases.
Exercise
You need the rule "each row's quantity is at least 1" and the rule "the order has at least one row". Where does each rule go in the schema function?
Show answer
The quantity rule goes inside applyEach(path.items, (item) => { min(item.quantity, 1); }), so it applies to every row. The "at least one row" rule goes on the array field, for example validate(path.items, ({ value }) => value().length > 0 ? null : { kind: 'no-items', message: 'Add at least one item' }). It cannot go in applyEach, because that callback does not run when the array is empty.