Reactive Forms
While template-driven forms are simple, reactive forms give you more control and better testability. You define the form structure and validation rules in the component class, making the logic easier to manage, especially for complex forms.
Reactive forms use the
FormGroup, FormControl, and FormArray classes. You build the form model in the component and bind it to the template.Basic Example: Login Form with Reactive Forms
Component class:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-login-reactive',
templateUrl: './login-reactive.component.html'
})
export class LoginReactiveComponent implements OnInit {
loginForm: FormGroup;
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required, Validators.minLength(6)])
});
}
onSubmit() {
if (this.loginForm.valid) {
console.log('Form submitted:', this.loginForm.value);
}
}
}
Template (login-reactive.component.html):
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div>
<label>Email:</label>
<input type="email" formControlName="email">
<div *ngIf="loginForm.get('email').invalid && loginForm.get('email').touched">
<small *ngIf="loginForm.get('email').errors?.required">Email is required.</small>
<small *ngIf="loginForm.get('email').errors?.email">Enter a valid email.</small>
</div>
</div>
<div>
<label>Password:</label>
<input type="password" formControlName="password">
<div *ngIf="loginForm.get('password').invalid && loginForm.get('password').touched">
<small *ngIf="loginForm.get('password').errors?.required">Password is required.</small>
<small *ngIf="loginForm.get('password').errors?.minlength">Password must be at least 6 characters.</small>
</div>
</div>
<button type="submit" [disabled]="loginForm.invalid">Login</button>
</form>
Using FormBuilder (Convenience)
Angular provides
FormBuilder to create forms with less boilerplate:import { FormBuilder } from '@angular/forms';
export class LoginComponent {
loginForm = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
constructor(private fb: FormBuilder) { }
}
Two Minute Drill
- Reactive forms are defined in the component class using FormGroup, FormControl.
- Bind form in template with [formGroup] and formControlName.
- Validation is set up using Validators class.
- FormBuilder provides a cleaner syntax.
- Better for complex forms, dynamic forms, and unit testing.
Need more clarification?
Drop us an email at career@quipoinfotech.com
