Sub topic 2
Read Field State as Signals
Assume you know TypeScript, standalone Angular components, templates, and Angular signals. Signal Forms is experimental in Angular 21, so its API may change.
Read field state as signals
A Signal Form derives field state from a writable signal model. A field is callable: loginForm.email() returns the field state. Its properties are signals, so call them to read their current values.
Common state signals include:
value(): the current field value.valid()andinvalid(): whether validation passes.touched(): whether the user has focused and left the field.dirty(): whether the user changed the value.errors(): the current validation errors.
The form itself is also callable. For example, loginForm().invalid() checks the whole form.
import { Component, signal } from '@angular/core';
import { form, Field, required, email } from '@angular/forms/signals';
@Component({
selector: 'app-login',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>
Email
<input type="email" [field]="loginForm.email" />
</label>
@if (loginForm.email().touched() && loginForm.email().invalid()) {
@for (error of loginForm.email().errors(); track error.kind) {
<p>{{ error.message }}</p>
}
}
<button type="submit" [disabled]="loginForm().invalid()">
Log in
</button>
</form>
`,
})
export class LoginComponent {
private readonly model = signal({ email: '' });
protected readonly loginForm = form(this.model, (path) => {
required(path.email, { message: 'Email is required' });
email(path.email, { message: 'Enter a valid email address' });
});
protected onSubmit(event: Event) {
event.preventDefault();
console.log(this.model());
}
}Add built-in validators
A schema function declares validation rules for model paths. Built-in validators such as required, email, and minLength update field validity when the model changes.
Show validation errors to the user
Check touched() before showing errors. This avoids displaying an error before the user interacts with the field. Iterate over errors() because one field can have multiple failed rules.
Submit the form
Use submit() when saving data. It marks fields as touched, checks validity, and runs the action only for a valid form. An action can return an error object for a server-side failure.
import { form, submit } from '@angular/forms/signals';
const profile = signal({ name: '' });
const profileForm = form(profile);
async function save() {
await submit(profileForm, async (currentForm) => {
const response = await fetch('/api/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(currentForm().value()),
});
if (!response.ok) {
return { kind: 'server', message: 'Saving failed.' };
}
return undefined;
});
}Exercise
Why should a template usually check touched() before displaying errors?
Show answer
It prevents validation messages from appearing before the user has interacted with the field.