Many Angular apps written before Signal Forms use reactive forms. This part covers FormControl, FormGroup, FormArray, FormBuilder, typed forms, validators and errors, so you can read and fix that code.
New Angular code uses Signal Forms, which we built in Part 21 and Part 22. But many Angular apps you’ll open at work were written before Signal Forms existed. Their forms are reactive forms: FormGroup, FormControl and friends, from the same @angular/forms package. You need to read them, fix them, and sometimes add a field to them.
This part covers the pieces of a reactive form, typed forms and why null keeps turning up in their types, validators and error messages, lists of fields with FormArray, setValue, patchValue and reset, and how a reactive form behaves in a zoneless Angular 22 app, with toSignal from Part 20 as the bridge. It ends with a table that maps each idea to its Signal Forms twin. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.
Try this first
Here’s a small profile form, the kind you’d find in an existing app. It has two fields and a preview line. Load saved pretends to fetch a saved profile from a server, with a timer standing in for the network.
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
</form>
<p>Preview: {{ profile.value.name }} ({{ profile.value.email }})</p>
<button (click)="loadSaved()">Load saved</button>
`,
})
export class App {
protected readonly profile = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
});
protected loadSaved() {
setTimeout(() => {
this.profile.setValue({ name: 'Ana', email: 'ana@example.com' });
}, 100);
}
}
Before you read on, guess. Type Ana into Name. What does the preview say? Then reload the page and click Load saved. What do the boxes show, and what does the preview say?
Here’s what happens. After you type Ana, the page shows:
Name Email
Preview: Ana ()
Load saved
(The page text doesn’t include what’s typed in the boxes, so you only see the labels here.) Now reload and click Load saved. The boxes fill in with Ana and her email. The preview stays empty:
Name Email
Preview: ()
Load saved
The form’s value is right. The boxes are right. Only the preview is stale. We’ll see why after we’ve named the pieces.
The pieces of a reactive form
A reactive form is a tree of objects you build in the class. The template then connects its inputs to that tree.
- A
FormControlholds one value, like the text in one input. It also tracks that value’s state: is it valid, has the user touched it, has the user changed it. - A
FormGroupholds named controls. Its value is an object with one key per control:{ name: 'Ana', email: 'ana@example.com' }. - A
FormArrayholds a list of controls. Its value is an array. We’ll use one later for a list of tags.
All three come from @angular/forms. So do the directives that connect them to the template, which come in ReactiveFormsModule. You add it to the component’s imports, as with any directive from Part 11:
[formGroup]="profile"on the<form>connects the element to the group.formControlName="name"on an<input>connects that input to the control callednamein the nearest group.
The connection works both ways. When you type, the directive copies the text into the control. When code calls setValue, the directive writes the new value straight into the input element. That’s why the boxes filled in from the timer.
The build doesn’t check the text in formControlName. Here’s a typo:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile">
<label>Name <input formControlName="nmae" /></label>
</form>
`,
})
export class App {
protected readonly profile = new FormGroup({
name: new FormControl(''),
});
}
It builds. The page draws the label and the box, and the console shows an error that starts like this:
ERROR RuntimeError: NG01055: Cannot find control with path: 'nmae'. Controls that do exist at this level: name.
The message names the path it looked for and lists the controls that do exist. Search the template for the name in quotes, and fix the spelling.
In the class, profile.controls.name is the name control itself, with its full type. Older code often writes profile.get('name') instead. That works too, but it may return null, so the code that follows needs a ? or a !.
Here’s the tree for a slightly bigger form: a name, an email that’s disabled (the user can’t edit it) and a list of tags.
A reactive form is a tree of controls in the class. Directives in the template connect inputs to its nodes by name.
Why the preview stayed empty
Remember the rule from Part 3: in a new Angular 22 app, a component is redrawn after an event in its template, or when a signal its template read changes. There’s no zone.js watching every timer.
When you typed, the input’s input event fired. A directive on the input listens for that event, on an element in our template, so it counts as a template event, and the component was redrawn. The preview picked up the new value.
The timer is not a template event. setValue changed the controls, and the directive wrote the values into the boxes. But profile.value is a plain property. Reading it in the template doesn’t make Angular watch it, so nothing asked for a redraw.
Some of a control’s state is kept in signals inside the class: status, touched and pristine. Your template doesn’t read those signals directly, because the status, touched and pristine properties read them untracked: without telling Angular that the template depends on them. But the ng-valid, ng-invalid, ng-touched and ng-dirty CSS classes that formControlName and [formGroup] put on your elements do read them. So when a timer flips a bound form’s status, say from INVALID to VALID, those classes change, the component is redrawn, and everything in the template is redrawn with it, including the stale value. That’s why this bug can hide. Exercise 3 shows it.
Don’t rely on it. errors and value aren’t covered, and a control that isn’t bound to any element isn’t covered at all. Here’s one with no input:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<p>Status: {{ code.status }}</p>
<button (click)="fillLater()">Fill later</button>
`,
})
export class App {
protected readonly code = new FormControl('', Validators.required);
protected fillLater() {
setTimeout(() => this.code.setValue('A1'), 100);
}
}
Click Fill later and wait. The control is now valid, but the page shows:
Status: INVALID
Fill later
The fix: valueChanges and toSignal
Every control has two Observables (the RxJS streams from Part 20):
valueChangessends the new value every time it changes: when the user types, and when code callssetValue,patchValueorreset(unless called withemitEvent: false).statusChangessends the new status:'VALID','INVALID','PENDING'(an async validator is running) or'DISABLED'.
Neither sends the current value when you subscribe. They only send changes. So when you turn one into a signal with toSignal, give it an initialValue:
// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
</form>
<p>Preview: {{ value().name }} ({{ value().email }})</p>
<button (click)="loadSaved()">Load saved</button>
`,
})
export class App {
protected readonly profile = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
});
protected readonly value = toSignal(this.profile.valueChanges, {
initialValue: this.profile.value,
});
protected loadSaved() {
setTimeout(() => {
this.profile.setValue({ name: 'Ana', email: 'ana@example.com' });
}, 100);
}
}
Click Load saved and wait. The page shows:
Name Email
Preview: Ana (ana@example.com)
Load saved
The template now reads a signal, and toSignal sets it on every change, wherever the change came from. toSignal also unsubscribes when the component is destroyed, as Part 20 showed. You may also meet events, a third Observable that sends one object for every kind of change.
Typed forms: where the null comes from
Since Angular 14, reactive forms are typed. new FormControl('') is a FormControl<string | null>: a control whose value is a string or null. The type is a union, written with |, which means “one of these”.
Why null, when we gave it a string? Because of reset(). By default, resetting a control sets its value to null, not back to where it started. The option nonNullable: true changes that: the control remembers its starting value, reset() goes back to it, and the type drops the null.
There’s a second surprise in the group’s type. A disabled control is left out of the group’s value. So TypeScript types profile.value with every key optional: each one may be undefined. getRawValue() returns every control, disabled or not, with the full type.
Here’s both at once:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<button (click)="show()">Show</button>
<button (click)="reset()">Reset</button>
`,
})
export class App {
private readonly profile = new FormGroup({
name: new FormControl('Ana'),
email: new FormControl({ value: 'ana@example.com', disabled: true }),
city: new FormControl('Lima', { nonNullable: true }),
});
protected show() {
console.log('value', JSON.stringify(this.profile.value));
console.log('raw', JSON.stringify(this.profile.getRawValue()));
}
protected reset() {
this.profile.reset();
this.show();
}
}
new FormControl({ value: ..., disabled: true }) starts a control disabled. JSON.stringify turns an object into text, so we can log it on one line. Click Show, then Reset. The console shows:
value {"name":"Ana","city":"Lima"}
raw {"name":"Ana","email":"ana@example.com","city":"Lima"}
value {"name":null,"city":"Lima"}
raw {"name":null,"email":null,"city":"Lima"}
Read it line by line. value has no email, because email is disabled. getRawValue() has it. After reset(), name and email are null, and city, the nonNullable one, went back to 'Lima'.
So the types tell the truth: profile.value.name really can be a string, null or undefined. The second worked example shows the build error you get when you forget.
FormBuilder and NonNullableFormBuilder
Writing new FormControl('', { nonNullable: true }) for every field gets long. Most code uses FormBuilder, a service you get with inject() from Part 13. Its nonNullable version makes every control non-nullable:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="signup" (ngSubmit)="save()">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
<button type="submit">Sign up</button>
</form>
`,
})
export class App {
private readonly fb = inject(NonNullableFormBuilder);
protected readonly signup = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
protected save() {
console.log(this.signup.status, JSON.stringify(this.signup.getRawValue()));
}
}
Each key in fb.group({...}) becomes a control. ['', Validators.required] means “start with '', and use this validator”. A list of validators goes in its own array. signup is a FormGroup whose controls are all FormControl<string>, with no null.
inject(FormBuilder).nonNullable gives you the same builder. Plain inject(FormBuilder) makes nullable controls, like new FormControl('').
(ngSubmit) is an event from the [formGroup] directive. It fires when the form is submitted: by the submit button, or by pressing Enter in a field. Type Ana into Name and press Enter. The console shows:
INVALID {"name":"Ana","email":""}
The form still submits when it’s invalid. Checking that is your job, which brings us to validators.
Validators, errors and touched
A validator is a function that looks at a control’s value and returns either null (fine) or an errors object that says what’s wrong. The built-in ones are static methods on Validators:
Validators.requiredfails on an empty value, with the error{ required: true }.Validators.emailfails when the text isn’t shaped like an email address, with{ email: true }.Validators.minLength(3)fails when the text is shorter than 3, with{ minlength: { requiredLength: 3, actualLength: 1 } }. Note the lowercaselin the key.
A control’s errors holds all of its errors merged into one object, or null when it’s valid. hasError('minlength') asks about one. To show a message only after the user has had a chance to fill in a field, check touched: it turns true when the user leaves the field (the blur event). dirty turns true once the user changes the value.
Reading an error’s details has one trap. errors is typed as an object that can have any key, and a new Angular project turns on a TypeScript setting, noPropertyAccessFromIndexSignature, that wants such keys written with brackets. So the obvious code doesn’t build:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<label>Name <input [formControl]="name" /></label>
@if (name.errors?.minlength) {
<p>Too short</p>
}
`,
})
export class App {
protected readonly name = new FormControl('', Validators.minLength(3));
}
✘ [ERROR] TS4111: Property 'minlength' comes from an index signature, so it must be accessed with ['minlength']. [plugin angular-compiler]
The message says what to do: write name.errors?.['minlength']. (This example also shows [formControl], which connects an input to a control that isn’t in a group.)
Here’s a sign-up form that does it properly:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="signup" (ngSubmit)="save()">
<label>Name <input formControlName="name" /></label>
@if (name.touched && name.hasError('required')) {
<p>Name is required.</p>
}
@if (name.hasError('minlength')) {
<p>Name needs at least {{ name.errors?.['minlength'].requiredLength }} letters.</p>
}
<label>Email <input formControlName="email" /></label>
@if (email.touched && email.invalid) {
<p>Enter an email address.</p>
}
<button type="submit" [disabled]="signup.invalid">Sign up</button>
</form>
<p>Status: {{ signup.status }}</p>
`,
})
export class App {
private readonly fb = inject(NonNullableFormBuilder);
protected readonly signup = this.fb.group({
name: ['', [Validators.required, Validators.minLength(3)]],
email: ['', [Validators.required, Validators.email]],
});
protected readonly name = this.signup.controls.name;
protected readonly email = this.signup.controls.email;
protected save() {
console.log('saving', JSON.stringify(this.signup.getRawValue()));
}
}
name and email are shortcuts to the two controls, so the template stays short. When the page loads, the page shows:
Name Email Sign up
Status: INVALID
No messages yet, because nothing is touched. minLength doesn’t complain about an empty field; that’s required‘s job. Click into Name and press Tab to leave it. The page shows:
Name
Name is required.
Email Sign up
Status: INVALID
Tab moved you into Email. Now click back into Name and type Al. Clicking back leaves Email, so it’s touched too, and its message appears:
Name
Name needs at least 3 letters.
Email
Enter an email address.
Sign up
Status: INVALID
Now type Ana into Name and a@b into Email, then press Tab:
Name Email Sign up
Status: VALID
a@b passes. Validators.email checks the shape of the text, not whether the address exists, and a name without a dot after the @ is allowed. Click Sign up, and the console shows:
saving {"name":"Ana","email":"a@b"}
FormArray: a list of controls
When the user can add and remove fields, like a list of tags, the controls go in a FormArray. Its controls have no names, only positions:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile">
<div formArrayName="tags">
@for (tag of tags.controls; track tag; let i = $index) {
<input [formControlName]="i" [attr.aria-label]="'Tag ' + (i + 1)" />
<button type="button" (click)="tags.removeAt(i)">Remove {{ i + 1 }}</button>
}
</div>
<button type="button" (click)="addTag()">Add tag</button>
</form>
<p>Tags: {{ tags.value.join(', ') }} ({{ tags.status }})</p>
`,
})
export class App {
private readonly fb = inject(NonNullableFormBuilder);
protected readonly profile = this.fb.group({
tags: this.fb.array([this.fb.control('news')]),
});
protected readonly tags = this.profile.controls.tags;
protected addTag() {
this.tags.push(this.fb.control('', Validators.required));
}
}
The parts:
fb.array([...])makes aFormArray. Here it starts with one control holding'news'.formArrayName="tags"connects thedivto the array, the wayformControlNameconnects an input to a control.- Inside it,
[formControlName]="i"connects each input by its position. It’s a property binding becauseiis a number from the loop, not fixed text. pushadds a control at the end,removeAt(i)removes the one at positioni. Other methods you’ll see areinsert,at(i)andclear().track tagtracks each control object itself, so@forfrom Part 4 keeps each input with its control when one is removed.type="button"stops these buttons from submitting the form.
Click Add tag. The new tag is empty and required, so the array is invalid:
Remove 1Remove 2
Add tag
Tags: news, (INVALID)
The inputs don’t show up in the page text, so the first line is the two Remove buttons. They run together as Remove 1Remove 2 because buttons sit on one line, and the page text joins them. Type tips into Tag 2, then click Remove 1:
Remove 1
Add tag
Tags: tips (VALID)
The tips control moved to position 0, and its button is now Remove 1.
setValue, patchValue and reset
Three methods change a form’s value from code. Each one exists on controls, groups and arrays.
setValue(v)replaces the whole value. On a group, you must give every key. A missing key is a build error with typed forms, and a runtime error in untyped code.patchValue(v)changes only the keys you give. Use it for a partial update, like data from a server that only has some fields.reset(v?)sets the value (tov, or to the starting values for non-nullable controls, ornull), and marks everything as untouched and pristine again.
None of them marks a control as dirty or touched. Those flags are about what the user did.
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
<p>{{ profile.value.name }}, {{ profile.value.city }}</p>
<button (click)="patch()">Patch</button>
<button (click)="set()">Set</button>
<button (click)="profile.reset()">Reset</button>
`,
})
export class App {
protected readonly profile = inject(NonNullableFormBuilder).group({
name: 'Ana',
city: 'Lima',
});
protected patch() {
this.profile.patchValue({ city: 'Pune' });
}
protected set() {
this.profile.setValue({ name: 'Ben', city: 'Oslo' });
}
}
fb.group({ name: 'Ana' }) with a plain value and no validators is the shortest way to write a control. The buttons are template events, so reading profile.value in the template is fine here. Click Patch:
Ana, Pune
PatchSetReset
The three buttons run together as PatchSetReset, as the Remove buttons did. Click Set, then Reset:
Ben, Oslo
PatchSetReset
Ana, Lima
PatchSetReset
Reset went back to the values the form started with, because the builder made non-nullable controls. Now try setValue with a key missing:
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
template: `<button (click)="set()">Set</button>`,
})
export class App {
private readonly profile = inject(NonNullableFormBuilder).group({
name: 'Ana',
city: 'Lima',
});
protected set() {
this.profile.setValue({ name: 'Ben' });
}
}
✘ [ERROR] TS2345: Argument of type '{ name: string; }' is not assignable to parameter of type '{ name: string; city: string; }'.
Property 'city' is missing in type '{ name: string; }' but required in type '{ name: string; city: string; }'. [plugin angular-compiler]
setValue wants the whole object. If you meant to change one field, that’s patchValue.
Worked example: an edit-profile form
Here’s a form close to what you’d find in a real app. It loads a saved profile, lets the user edit the name, shows the email but doesn’t let them change it, and says when there are unsaved changes.
// src/app/app.ts
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
interface Profile {
name: string;
email: string;
}
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile" (ngSubmit)="save()">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
<button type="submit" [disabled]="profile.invalid || profile.pristine">Save</button>
</form>
<p>Hello, {{ value().name || 'stranger' }}</p>
@if (profile.dirty) {
<p>Unsaved changes</p>
}
`,
})
export class App {
private readonly fb = inject(NonNullableFormBuilder);
protected readonly profile = this.fb.group({
name: ['', Validators.required],
email: [{ value: '', disabled: true }],
});
protected readonly value = toSignal(this.profile.valueChanges, {
initialValue: this.profile.value,
});
constructor() {
setTimeout(() => {
this.profile.reset({ name: 'Ana', email: 'ana@example.com' });
}, 100);
}
protected save() {
const saved: Profile = this.profile.getRawValue();
console.log('saved', JSON.stringify(saved));
this.profile.markAsPristine();
}
}
What each part does:
- The timer in the constructor stands in for loading the profile from a server. A real app would use
httpResourcefrom Part 19 orHttpClientfrom Part 18. - It loads with
reset(...), notsetValue. Both set the value, butresetalso leaves the form pristine and untouched, so loaded data doesn’t count as the user’s change. { value: '', disabled: true }in the builder starts the email disabled. The input shows it greyed out.- The greeting reads
value(), thetoSignalbridge, because the value changes from a timer. profile.dirtyandprofile.pristineare read straight from the form. They change only when the user types or submits, and those are template events, so the page redraws anyway.save()usesgetRawValue(), so the disabled email is included, and TypeScript is happy to call it aProfile.markAsPristine()clears the dirty flag after saving.
Once the profile has loaded, the page shows:
Name Email Save
Hello, Ana
The Save button is disabled, because nothing has changed. Type Ana Lee into Name:
Name Email Save
Hello, Ana Lee
Unsaved changes
Click Save. The console shows:
saved {"name":"Ana Lee","email":"ana@example.com"}
and “Unsaved changes” goes away:
Name Email Save
Hello, Ana Lee
Worked example: reading a typed-form build error
You’re asked to add a Save button to an older form. The service it calls takes a Profile, with a string name and email. The first try passes form.value:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
interface Profile {
name: string;
email: string;
}
function saveProfile(profile: Profile) {
console.log('saved', profile.name, profile.email);
}
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
<button type="submit">Save</button>
</form>
`,
})
export class App {
protected readonly form = new FormGroup({
name: new FormControl('Ana'),
email: new FormControl('ana@example.com'),
});
protected save() {
saveProfile(this.form.value);
}
}
The build stops:
✘ [ERROR] TS2345: Argument of type 'Partial<{ name: string | null; email: string | null; }>' is not assignable to parameter of type 'Profile'.
Types of property 'name' are incompatible.
Type 'string | null | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'. [plugin angular-compiler]
Read it from the top, one indent at a time:
TS2345is TypeScript’s “wrong argument type” error.Partial<{ name: string | null; email: string | null; }>is the type ofform.value.Partial<...>means every key is optional, because a disabled control would be left out.string | nullinside it is each control’s type, becausenew FormControl('Ana')is nullable.- The last two lines narrow it down:
namecould beundefined(fromPartial) ornull(from the control), andProfilewants astring. TypeScript reports the first problem it finds,undefined.
Two changes fix the two causes. getRawValue() removes the Partial. nonNullable: true removes the null:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
interface Profile {
name: string;
email: string;
}
function saveProfile(profile: Profile) {
console.log('saved', profile.name, profile.email);
}
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
<button type="submit">Save</button>
</form>
`,
})
export class App {
protected readonly form = new FormGroup({
name: new FormControl('Ana', { nonNullable: true }),
email: new FormControl('ana@example.com', { nonNullable: true }),
});
protected save() {
saveProfile(this.form.getRawValue());
}
}
Click Save. The console shows:
saved Ana ana@example.com
Don’t fix this with this.form.value as Profile. That silences the error, and a reset form would then send null to a function that expects a string.
Reactive forms next to Signal Forms
If you know Signal Forms from Parts 21 and 22, here’s where each idea lives in a reactive form:
| Reactive forms | Signal Forms |
|---|---|
FormGroup / FormControl built in the class; the form holds the value |
form(model) over a signal you own; the signal holds the value |
ReactiveFormsModule, [formGroup], formControlName |
FormField, [formField]="f.name" |
profile.value (plain property), getRawValue() |
f().value() and model(), both signals |
valueChanges, statusChanges (Observables) |
the state is signals already |
status, valid, errors, touched, dirty (properties) |
f.name().valid(), errors(), touched(), dirty() (signals) |
Validators.required, Validators.email, Validators.minLength(3) |
required(p.name), email(p.email), minLength(p.name, 3) in the schema |
errors is an object: { minlength: {...} } |
errors() is a list of error objects with a kind |
FormArray, push, removeAt |
an array in the model, changed with update, with applyEach for rules |
disabled controls left out of value |
disabled(...) rule; the model still has the value |
(ngSubmit) |
submit(f, ...), or [formRoot] with submission |
You don’t have to move a whole app at once. Angular 22 has a bridge in @angular/forms/signals/compat: compatForm builds a signal form whose model can hold existing FormControls, and SignalFormControl is a control built from Signal Forms rules that you can put inside an existing FormGroup. We haven’t covered them in this series. If you’re migrating a large form, angular.dev’s Signal Forms migration guide is the place to start.
You may also meet: template-driven forms
Some older code uses a third style. It imports FormsModule instead of ReactiveFormsModule and writes [(ngModel)]="user.name" on each input, with validators as attributes like required and minlength="3". Angular builds the controls for you from the template. It’s the same FormControl underneath, but there’s no tree in the class to read. When you see ngModel, that’s what it is.
In older code
Reactive forms code from before Angular 14 and before inject() looks a little different:
UntypedFormGroup,UntypedFormControlandUntypedFormBuilderare the old untyped forms, where every value isany. Angular’s update to v14 renamed old forms to these so they kept building. You can type them one by one.constructor(private fb: FormBuilder) {}gets the builder through the constructor instead ofinject().this.form.get('address.city')reaches a nested control by a dotted path.this.form.valueChanges.subscribe(...)inngOnInit, often with no unsubscribe. That’s the leak Part 20 covered. UsetoSignal, ortakeUntilDestroyed.
Best practices
- In new code, use Signal Forms. They’re stable in Angular 22, and the state is signals from the start. Reactive forms are for code that already uses them.
- Make controls non-nullable. Use
NonNullableFormBuilderornonNullable: true.reset()then returns to the starting values, andnullis gone from your types. It replaces?? ''scattered through the code. - Send
getRawValue(), notvalue. It includes disabled controls and has the full type. It replacesform.value as Profile. - Bridge the value with
toSignal(form.valueChanges, { initialValue: form.value })when the template shows a value that code can change. It replaces readingform.valuein the template and hoping something else causes a redraw. - Load data with
reset(data)orpatchValue(data), notsetValue, unless you have every field.resetalso clears touched and dirty, which is what you want after loading.
Tips and traps
- A preview or summary that doesn’t update after a timer or a server response. The template reads
form.value, a plain property. Bridge it withtoSignal(form.valueChanges, ...). - A bug that only shows sometimes. The same stale value updates when the change also flips the status, because the
ng-valid/ng-invalidclasses on bound elements read the status and cause a redraw. If a value is right only when the form becomes valid, it’s the same cause and the same fix. TS4111onerrors?.minlength. Writeerrors?.['minlength']. Remember the lowercase key:minlength,maxlength.- Error messages showing as soon as the page loads.
errorsis set from the start. Checktouched(ordirty) as well. - A field missing from the saved data. It’s disabled, and
valueleaves disabled controls out. UsegetRawValue(). NG01055: Cannot find control with pathin the console. The text informControlNamedoesn’t match a key in the group. The build doesn’t check these names; fix the spelling.
A reactive form is a tree of controls in the class; when code can change it, read its value through
toSignal.
Exercises
Exercise 1. This form has a Clear button. After you type Ana and click Clear, the box empties, but the form’s value would then have null for the name. Change one thing so that Clear goes back to an empty string, and the type of form.value.name no longer includes null.
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<label>Name <input formControlName="name" /></label>
</form>
<button (click)="clear()">Clear</button>
`,
})
export class App {
protected readonly form = new FormGroup({
name: new FormControl(''),
});
protected clear() {
this.form.reset();
console.log(JSON.stringify(this.form.value));
}
}
{"name":null}
Exercise 2. Write a form with one Username field that’s required and at least 4 characters long. Below it, show Too short: 2 of 4 (with the real numbers) when the value is too short, and Status: VALID or Status: INVALID. After typing Al, the page should show Too short: 2 of 4 and Status: INVALID.
Exercise 3. Take the “Try this first” form, where Load saved left the preview empty, and add Validators.required to the name control. Without changing anything else, click Load saved again. Now the preview does update. Why? Is the form fixed?
Answers
1. Make the control non-nullable. reset() then goes back to '', and the type is FormControl<string>:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<label>Name <input formControlName="name" /></label>
</form>
<button (click)="clear()">Clear</button>
`,
})
export class App {
protected readonly form = new FormGroup({
name: new FormControl('', { nonNullable: true }),
});
protected clear() {
this.form.reset();
console.log(JSON.stringify(this.form.value));
}
}
Type Ana and click Clear. The console shows:
{"name":""}
form.value.name is now string | undefined. The undefined is still there because value is Partial; getRawValue().name is a plain string.
2. Use minLength(4) and read its details with brackets:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<label>Username <input [formControl]="username" /></label>
@if (username.errors?.['minlength']; as tooShort) {
<p>Too short: {{ tooShort.actualLength }} of {{ tooShort.requiredLength }}</p>
}
<p>Status: {{ username.status }}</p>
`,
})
export class App {
protected readonly username = new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(4)],
});
}
@if (...; as tooShort) gives the error’s details a name for the block. The options object with validators is another way to give a control its validators. Type Al into Username. The page shows:
Username
Too short: 2 of 4
Status: INVALID
3. Here’s the change:
// src/app/app.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="profile">
<label>Name <input formControlName="name" /></label>
<label>Email <input formControlName="email" /></label>
</form>
<p>Preview: {{ profile.value.name }} ({{ profile.value.email }})</p>
<button (click)="loadSaved()">Load saved</button>
`,
})
export class App {
protected readonly profile = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl(''),
});
protected loadSaved() {
setTimeout(() => {
this.profile.setValue({ name: 'Ana', email: 'ana@example.com' });
}, 100);
}
}
Click Load saved and wait. The page shows:
Name Email
Preview: Ana (ana@example.com)
Load saved
The empty name made the form INVALID. Loading Ana made it VALID. The ng-valid and ng-invalid classes on the inputs and the form read the status as a signal, so that change scheduled a redraw, and the redraw read the new value too. The form isn’t fixed. It works only because the status happened to change. Load a second profile while the form is already valid, and the preview would stay stale again. The real fix is still toSignal(profile.valueChanges, ...).
What’s next
We’ve now seen both kinds of form Angular has, and Parts 21 and 22 showed the one to write new code with. In Part 24, we’ll test components with Vitest and TestBed: render one, click and type in it, and check what it shows.