Introduction:
Template-driven forms and Reactive forms are two approaches to handling forms in Angular applications. Each approach has its strengths and weaknesses, and choosing the right one depends on the complexity and requirements of the form. In this blog, we will explore Template-driven forms and Reactive forms in Angular, compare their features, and provide examples for better understanding.
If you want to learn one more feature of angular, you can refer here.
Template-driven Forms
These forms are a simple and declarative way to work with forms in Angular. They rely on directives, such as ngModel
, binding form controls to the data model. These forms are defined in the HTML itself and require minimal TypeScript code.
Features of Template-driven Forms:
- Minimal TypeScript Code: Template-driven forms are easier to set up and require less TypeScript code compared to Reactive forms.
- Two-way Data Binding: Template-driven forms use two-way data binding with
ngModel
, allowing the form controls to automatically update the data model and vice versa. - Automatic Validation: Angular automatically performs form validation based on HTML attributes like
required
,min
,max
, etc. - Suitable for Simple Forms: Template-driven forms are ideal for simple forms with straightforward data binding and validation requirements.
Example: Creating a Template-driven Form
Let’s create a simple login form using Template-driven forms.
Step 1: Create the Form in the Component Template
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email" [(ngModel)]="user.email" required>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password" [(ngModel)]="user.password" required>
</div>
<button type="submit">Submit</button>
</form>
Step 2: Implement the Form Handling in the Component
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
})
export class LoginComponent {
user = { email: '', password: '' };
onSubmit(form: any): void {
if (form.valid) {
console.log('Form submitted:', this.user);
}
}
}
Reactive Forms
Reactive forms, on the other hand, offer more control and flexibility when working with complex forms. They are based on reactive programming principles and involve creating form controls programmatically in the component class.
Features of Reactive Forms:
- Full Programmatic Control: Reactive forms allow complete control over form elements, making them suitable for complex forms and dynamic form elements.
- Immutable Form State: The form state is immutable in Reactive forms, enabling better tracking of form changes and easier testing.
- Advanced Validation: Reactive forms provide powerful and custom validation mechanisms, including synchronous and asynchronous validators.
- Dynamic Form Control Handling: Reactive forms allow adding, removing, and disabling form controls dynamically.
Example: Creating a Reactive Form
Let’s create the same login form using Reactive forms.
Step 1: Create the Form in the Component Class
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit(): void {
this.loginForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required],
});
}
onSubmit(): void {
if (this.loginForm.valid) {
console.log('Form submitted:', this.loginForm.value);
}
}
}
Step 2: Bind the Form to the Template
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div>
<label for="email">Email</label>
<input type="email" id="email" formControlName="email">
<div *ngIf="loginForm.get('email').invalid && loginForm.get('email').touched">
<p *ngIf="loginForm.get('email').hasError('required')">Email is required</p>
<p *ngIf="loginForm.get('email').hasError('email')">Invalid email format</p>
</div>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" formControlName="password">
<div *ngIf="loginForm.get('password').invalid && loginForm.get('password').touched">
<p *ngIf="loginForm.get('password').hasError('required')">Password is required</p>
</div>
</div>
<button type="submit">Submit</button>
</form>
Comparison: Template-driven Forms vs. Reactive Forms
- Code Complexity: Template-driven forms require less TypeScript code and are easier to set up, while Reactive forms involve more TypeScript code but offer more control and flexibility.
- Two-way Data Binding: Template-driven forms use two-way data binding with
ngModel
, while Reactive forms use one-way data binding with form controls. - Validation: Template-driven forms provide automatic validation based on HTML attributes, whereas Reactive forms provide more advanced and custom validation options.
- Dynamic Forms: Reactive forms handle dynamic form control creation and manipulation more effectively.
- Immutability: Reactive forms offer an immutable form state, making it easier to track form changes and integrate with state management libraries.
Conclusion
Both Template-driven forms and Reactive forms are powerful ways to handle forms in Angular applications. Template-driven forms are suitable for simple forms with basic validation requirements, while Reactive forms offer more control and advanced validation capabilities, making them ideal for complex and dynamic forms.
In this blog, we explored the features of Template-driven and Reactive forms in Angular and provided examples of creating a simple login form using each approach. Understanding the strengths and weaknesses of each approach will help you choose the most appropriate form-handling method for your Angular application. Happy form handling and coding in Angular!
Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.