Angular has introduced native Signal-based Forms in Angular 21, moving away from RxJS-heavy Reactive Forms for modern apps. Let's explore how this fine-grained reactivity system handles validation, submission, and dynamic controls with absolute simplicity.
Why Signal Forms?
Standard reactive forms in Angular rely on RxJS Observables (like valueChanges and statusChanges). While powerful, it introduces overhead and requires manual cleanup to avoid memory leaks. Signal Forms use Angular Signals to track form value changes, ensuring only the exact components affected by a change are re-rendered.
Example: Creating a Login Form
Let's write a simple login component with signals:
import { Component, signal } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login-form',
template: `
<form (submit)="onSubmit()">
<div>
<label>Email</label>
<input [formControl]="emailControl" />
@if (emailControl.invalid() && emailControl.touched()) {
<span class="error">Invalid email address</span>
}
</div>
<button [disabled]="formGroup.invalid()">Submit</button>
</form>
`
})
export class LoginFormComponent {
emailControl = new FormControl('', {
validators: [Validators.required, Validators.email]
});
formGroup = new FormGroup({
email: this.emailControl
});
onSubmit() {
if (this.formGroup.valid()) {
console.log('Submitted values:', this.formGroup.value());
}
}
}Benefits of Angular 21 Signal Forms
- No Subscriptions: You read values directly via signals (e.g.
control.value()) in templates. - Synchronous Reactivity: Signal updates are tracked immediately, resolving template changes without checking the entire component tree.
- Cleaner Testing: Testing form controls is easier since values can be updated directly via
.set()or.update()on the controls.
Signal Forms mark a new chapter in Angular development, bringing reactivity in line with modern web development paradigms.
