Reactive form validation in Angular lets you define validation rules programmatically using Validators. This gives you full control over how each form control behaves, making it ideal for complex and dynamic forms.
In a reactive form:
FormGroup and FormControl objects in the TypeScript code.Validators (like required, email, minLength).[formGroup] and formControlName.Typical steps to build a reactive form with validation:
FormGroup, FormControl and Validators from @angular/forms.FormGroup instance and configure each control with its validators.FormGroup to the template using [formGroup].formControlName.errors and touched state.[disabled]="userForm.invalid".⚙️ Pattern: Define validations in TS ➜ Show messages in template
// Define a reactive form with validation rules
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
email: new FormControl('', [Validators.required, Validators.email])
});
submitForm() {
console.log('Form Submitted', this.userForm.value);
}
}
<!-- Bind the reactive form and show validation messages -->
<form [formGroup]="userForm" (ngSubmit)="submitForm()">
<label>Name:</label>
<input type="text" formControlName="name">
<div class="error" *ngIf="userForm.get('name')?.errors && userForm.get('name')?.touched">
<span *ngIf="userForm.get('name')?.errors?.required">Name is required.</span>
<span *ngIf="userForm.get('name')?.errors?.minlength">Name must be at least 3 characters.</span>
</div>
<br><br>
<label>Email:</label>
<input type="email" formControlName="email">
<div class="error" *ngIf="userForm.get('email')?.errors && userForm.get('email')?.touched">
<span *ngIf="userForm.get('email')?.errors?.required">Email is required.</span>
<span *ngIf="userForm.get('email')?.errors?.email">Invalid email format.</span>
</div>
<br><br>
<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
userForm is valid.console.log.userForm.get('controlName') to access the state, value, and errors of any control.touched or dirty flags to avoid showing errors before the user interacts.ReactiveFormsModule in your feature or root module before using reactive forms.FormGroups for complex forms (e.g., address, profile).Validators.required and Validators.minLength(6).FormGroup to ensure both passwords match.valueChanges observable).