Reactive Forms
In Reactive Forms, the validation logics and control are kept separated from the view template. These are managed programmatically in the component class using FormBuilder, FormGroup, FormControl, and FormArray. The template is only responsible for the basic structure of the form. This helps in scalability and maintainability if the form logic becomes too complex. Reactive Forms gives more control to the developers with regards to form state, validation, and form value changes.
Syntax:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<input formControlName="name" required>
<button type="submit">Submit</button>
</form>
Features of Reactive Forms:
- Ideal for complex forms with dynamic fields and validation logic.
- Full control over form model and state.
- Immutable data model, making it easier to test and debug.
- Asynchronous form validation support.
- Easily integrate with custom form controls.
Example:
<!-- app.component.html -->
<h3>Complex Template Driven Form</h3>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<div>
<label for="name2">Name: </label
><input type="text" id="name2" formControlName="name" />
</div>
<div>
<label for="email2">Email: </label
><input type="email" id="email2" formControlName="email" />
</div>
<div>
<label for="password2">Password: </label
><input type="password" id="password2" formControlName="password" />
</div>
<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
// app.component.ts
import { Component } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
@Component({
selector: 'app-reactive-complex',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './reactive-complex.component.html',
styleUrl: './reactive-complex.component.css',
})
export class ReactiveComplexComponent {
userForm = new FormGroup({
name: new FormControl('', [Validators.required]),
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required]),
});
onSubmit() {
console.log(this.userForm.value);
}
}
Output:
Template Driven Form vs Reactive Form in Angular.
Angular provides two main approaches for creating forms: Template-Driven Forms and Reactive Forms. In this article, we’ll see both methods, highlighting their features, and providing code examples. We’ll also compare them side by side to help you understand when to use each.