Angular Reactive Forms give you full programmatic control over form state, validation, and submission. This lesson covers FormBuilder, Validators, custom validators, and wiring up error messages.
Import ReactiveFormsModule in your module, then build forms in the component class using FormBuilder.
imports: [ReactiveFormsModule]import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({ selector: 'app-registration', templateUrl: '...' })
export class RegistrationComponent {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
confirmPassword: ['', Validators.required]
}, { validators: this.passwordMatch });
}
// Custom cross-field validator
passwordMatch(group: FormGroup) {
const pw = group.get('password')?.value;
const confirm = group.get('confirmPassword')?.value;
return pw === confirm ? null : { mismatch: true };
}
get nameControl() { return this.form.get('name'); }
onSubmit() {
if (this.form.valid) {
console.log(this.form.value);
} else {
this.form.markAllAsTouched();
}
}
}form.get('email')?.errors?.['email']. The ?. optional chaining prevents errors when the control hasn't been touched yet.valueChanges observable.FormBuilder.group() creates a FormGroup with controls and validators.required, email, minLength, maxLength, pattern.control.invalid && control.touched to avoid red fields on page load.