Sub topic 12
Extract and reuse schemas
As a form grows, its schema function grows too. The same group of rules also tends to appear in more than one place: a shipping address and a billing address, or every row of a line-item list. This chapter shows how to move rules into named, reusable pieces and attach them where they are needed.
This chapter assumes you can already create a form with form(), add built-in validators, and write a simple custom validator. Signal Forms is experimental in Angular 21, so the function names below may change in later releases.
The problem: repeated rules
Suppose an order form collects two addresses. Written inline, the rules are duplicated:
const orderForm = form(model, (path) => {
required(path.shipping.street);
required(path.shipping.city);
required(path.shipping.postalCode);
required(path.billing.street);
required(path.billing.city);
required(path.billing.postalCode);
});Every change, such as a new postal-code pattern, must be made twice. The two copies will eventually drift apart.
Create a schema with schema()
A schema is a reusable set of rules for one shape of data. You create it with schema(), which takes a function that receives a path for the root of that shape. The type argument tells TypeScript what the shape is, so path.street and the other paths are type-checked.
import { schema, required, pattern } from '@angular/forms/signals';
export interface Address {
street: string;
city: string;
postalCode: string;
}
export const addressSchema = schema<Address>((path) => {
required(path.street, { message: 'Street is required' });
required(path.city, { message: 'City is required' });
required(path.postalCode, { message: 'Postal code is required' });
pattern(path.postalCode, /^\d{5}$/, { message: 'Use five digits' });
});The schema is a plain value. It is not tied to any form or component, so you can export it from its own file and import it anywhere.
Attach a schema with apply()
apply() takes a path in the form and a schema. It adds all the schema's rules to the field at that path and to the fields beneath it.
import { signal } from '@angular/core';
import { form, apply, required } from '@angular/forms/signals';
interface Order {
name: string;
shipping: Address;
billing: Address;
}
const model = signal<Order>({
name: '',
shipping: { street: '', city: '', postalCode: '' },
billing: { street: '', city: '', postalCode: '' },
});
const orderForm = form(model, (path) => {
required(path.name, { message: 'Name is required' });
apply(path.shipping, addressSchema);
apply(path.billing, addressSchema);
});The rules in addressSchema are written against Address. When you apply the schema to path.shipping, the schema's path.street becomes path.shipping.street. The same schema works at path.billing without any change.
The field tree is the same as if you had written the rules inline. You still read state as orderForm.shipping.city().errors() and bind inputs as [field]="orderForm.billing.postalCode".
Apply a schema only when a condition holds
Sometimes a group of rules should run only in certain states. A billing address is not needed when the customer ticks "same as shipping". applyWhen() takes a path, a condition function, and a schema. The schema's rules are active only while the condition returns true.
import { signal } from '@angular/core';
import { form, apply, applyWhen, required } from '@angular/forms/signals';
interface Checkout {
sameAsShipping: boolean;
shipping: Address;
billing: Address;
}
const checkoutModel = signal<Checkout>({
sameAsShipping: true,
shipping: { street: '', city: '', postalCode: '' },
billing: { street: '', city: '', postalCode: '' },
});
const checkoutForm = form(checkoutModel, (path) => {
apply(path.shipping, addressSchema);
applyWhen(
path.billing,
({ valueOf }) => !valueOf(path.sameAsShipping),
addressSchema,
);
});The condition is reactive. It reads sameAsShipping through valueOf(), so when the checkbox changes the billing rules switch on or off without extra code. While the rules are off, the billing fields report no errors from this schema.
This is the same idea as the when option on a single validator, which you saw in the conditional-logic chapter. applyWhen() applies it to a whole group of rules at once.
Apply a schema to every item in an array
A model that holds a list needs the same rules on each element. applyEach() takes the path to an array and a schema for one element.
import { signal } from '@angular/core';
import { form, schema, applyEach, required, min } from '@angular/forms/signals';
interface LineItem {
product: string;
quantity: number;
}
const lineItemSchema = schema<LineItem>((path) => {
required(path.product, { message: 'Choose a product' });
min(path.quantity, 1, { message: 'Quantity must be at least 1' });
});
const cartModel = signal({
items: [{ product: '', quantity: 1 }] as LineItem[],
});
const cartForm = form(cartModel, (path) => {
applyEach(path.items, lineItemSchema);
});When the model gains a new item, the field for that item gets the same rules automatically. The array chapter covers how to add and remove rows. What matters here is that the rules live in one schema and follow the data.
Schemas that take parameters
A schema is a value, so a normal function can build one. This is useful when the rules are the same but a number or message differs.
import { schema, required, minLength } from '@angular/forms/signals';
export function passwordSchema(minimum: number) {
return schema<string>((path) => {
required(path, { message: 'Password is required' });
minLength(path, minimum, {
message: `Use at least ${minimum} characters`,
});
});
}Here the root of the schema is a single string field, so the rules use path directly. You attach it with apply(path.password, passwordSchema(12)). An admin form might use 12 characters and a public one 8, with no duplicated rule code.
How rules combine
A field can receive rules from several sources: its own parent schema, an applied schema, and an applyWhen() block. The rules combine. Errors from all of them appear together in errors(), and the field is valid only if none of them reports an error.
This means you can layer rules. The shared addressSchema can hold the baseline, and the form that uses it can add one more rule for a single field:
const shippingForm = form(model, (path) => {
apply(path.shipping, addressSchema);
required(path.shipping.city, { message: 'We need a city to ship to' });
});Both required rules now apply to shipping.city. If the field is empty, errors() contains two entries. Their kind values are the same, so decide which message to show, or de-duplicate before you render. Adding a duplicate rule like this is usually a mistake. Prefer adding rules the shared schema does not have.
Gotchas
- Schemas see only their own subtree. Inside
addressSchema,pathis the address root. You cannot refer topath.sameAsShippingfrom there, because that field is outside theAddresstype. A rule that needs data from outside the shape belongs in the parent schema, or in anapplyWhen()condition written in the parent. - Keep the type argument. Write
schema<Address>(...). Without it, the path type may not be inferred as you expect, and you lose the compile-time check on field names. - Define schemas at module level. They are declarations, not state. Creating them once outside the component avoids rebuilding them for every component instance.
- Match the model shape.
apply(path.billing, addressSchema)only compiles whenbillinghas theAddressshape. If the shapes drift, the compiler tells you.
Where to place shared schemas
A practical layout keeps the schema next to the type it describes:
address.tsexports theAddressinterface andaddressSchema.line-item.tsexportsLineItemandlineItemSchema.- Each form file imports the schemas it needs and composes them in its
form()call.
Because a schema is plain TypeScript, you can unit test it without rendering a component. Create a form() from a small model inside a test, apply the schema, and assert on errors() for each field.
Exercise
A checkout form has a sameAsShipping boolean, a shipping address, and a billing address. Both addresses use addressSchema. How do you make the billing rules apply only when sameAsShipping is false, and why must that condition be written in the form's own schema function rather than inside addressSchema?
Show answer
Use applyWhen(path.billing, ({ valueOf }) => !valueOf(path.sameAsShipping), addressSchema) in the form's schema function, and use apply(path.shipping, addressSchema) for the shipping address. The condition must live in the form's schema function because addressSchema only sees the Address subtree, and sameAsShipping is outside that subtree. The parent schema can see the whole model, so it can read sameAsShipping and decide whether to apply the schema.
Exercise
You apply addressSchema to path.shipping and then also call required(path.shipping.city) in the form's schema function. What does shipping.city().errors() contain when the city is empty, and what would you do instead?
Show answer
It contains two required errors, one from each rule, because rules from different sources combine. Instead, remove the duplicate required call. Add only rules that addressSchema does not already contain, or change the shared schema if every address needs the new rule.