Reactive Forms in Depth
Reactive forms describe the form in TypeScript: each box is a FormControl, grouped in a FormGroup, with validation rules attached. They are great for bigger forms.
For real business apps - checkout, registration, admin screens - forms have many fields, rules that depend on each other, and values that load from the server. Reactive forms keep the whole form model in TypeScript, where it's easy to test, validate and change. The template just connects inputs to controls, and the form's value, validity and errors are always available in code.
Example
import { Component, inject } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-address-form',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<input formControlName="name" placeholder="Full name">
@if (form.controls.name.touched && form.controls.name.hasError('required')) {
<small class="err">Name is required</small>
}
<input formControlName="pin" placeholder="PIN code">
@if (form.controls.pin.touched && form.controls.pin.invalid) {
<small class="err">Enter a 6-digit PIN code</small>
}
<input formControlName="phone" placeholder="Mobile">
<label><input type="checkbox" formControlName="defaultAddress"> Make default</label>
<button [disabled]="form.invalid">Save address</button>
</form>
`,
})
export class AddressForm {
private fb = inject(FormBuilder);
form = this.fb.nonNullable.group({
name: ['', Validators.required],
pin: ['', [Validators.required, Validators.pattern(/^[1-9][0-9]{5}$/)]],
phone: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
defaultAddress: [false],
});
save() {
if (this.form.invalid) { this.form.markAllAsTouched(); return; }
console.log(this.form.getRawValue()); // { name, pin, phone, defaultAddress }
}
}Your own validator
Example
import { AbstractControl, ValidationErrors } from '@angular/forms';
export function noSpaces(control: AbstractControl): ValidationErrors | null {
return /\s/.test(control.value) ? { noSpaces: true } : null;
}
// username: ['', [Validators.required, noSpaces]]Listening to changes
Example
this.form.controls.pin.valueChanges.subscribe(pin => {
if (pin.length === 6) this.lookUpCity(pin);
});fb.nonNullable.group makes typed controls that reset to their start values instead of null. Angular is also adding "signal forms" - check the official docs when you're ready.Key points
- FormControl, FormGroup and FormBuilder describe the form in code.
- Validators check fields; write custom validators as functions.
- valueChanges lets you react as the user types.
📝 Test yourself
1. Which directive connects an input to a control in the group?
2. What does a validator return when the value is fine?
3. Fill in the method that shows all errors after a bad submit:
this.form.();
