Angular Reactive Forms give you full programmatic control over form state, validation, and submission. This lesson covers FormBuilder, Validators, custom v
Learn the core concepts of Reactive Forms and apply them in practical exercises.
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.Before moving on, confirm understanding of these key concepts: