Reactive Forms vs Template Driven Forms
Last Updated :
18 Apr, 2024
Angular provides two main approaches for handling forms: Reactive Forms and Template-Driven Forms. In this article, we'll learn more about Reactive Forms and Template-Driven Forms in detail.
Reactive Forms is a way through which we can build forms in Angular. It makes use of the component class to programmatically declare the form controls. The validations and other form controls are written in the component class. Then these written form controls are then bound to the input fields present in the html template.
Syntax:
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
// Create form controls and group them into a form group
const form = new FormGroup({
username: new FormControl(''),
email: new FormControl(''),
password: new FormControl('')
});
Features of Reactive Forms:
- Programmatic control: Since Reactive forms are made from the form controls made in the component class. So, it allows us to define the structure of the form, rules for validation purpose. It allows us to have a programmatic control over the form component.
- Model-Driven Approach: The whole structure of the form is defined using the TypeScript classes or in the component class rather than the template file. For larger applications, it is more easier to understand and maintain the form state and data.
- Integration with Backend Services: When it comes to integrate with the Backend services. It offers more flexibility as it is easier to integrate with the backend services.
- Dynamic Forms: Reactive forms provide the features of dynamically add or remove form controls. The form builder methods available makes the management of dynamic forms easier. We can have more control and conditionally display the form elements.
- Explicit Validation: Since, we have more programmatically code in our component class. So, we can have more custom validation functions to provide validations in the angular form state.
Example:
HTML
<!-- app.component.html -->
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div>
hello
<label for="username">Username:</label>
<input type="text" id="username" formControlName="username" />
<div
*ngIf="myForm.get('username').invalid && myForm.get('username').touched"
>
<small *ngIf="myForm.get('username').errors.required"
>Username is required.</small
>
</div>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email" />
<div *ngIf="myForm.get('email').invalid && myForm.get('email').touched">
<small *ngIf="myForm.get('email').errors.required"
>Email is required.</small
>
<small *ngIf="myForm.get('email').errors.email"
>Invalid email format.</small
>
</div>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" formControlName="password" />
<div
*ngIf="myForm.get('password').invalid && myForm.get('password').touched"
>
<small *ngIf="myForm.get('password').errors.required"
>Password is required.</small
>
</div>
</div>
<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
JavaScript
// app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', Validators.required),
});
}
onSubmit() {
if (this.myForm.valid) {
console.log(this.myForm.value);
}
}
}
export class MyFormComponent { }
JavaScript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
providers: [],
})
export class AppModule { }
Output:
After Submitting Button is clickedTemplate Driven Forms is the most simplest way through which we can build a form in Angular. It utilizes Angular's two-way data binding directive (ngModel). This helps the user to manage and create the form instance. The whole form is managed entirely in the view template. There is no or minimal need to write programmatically code in the typescript file.
Syntax:
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<input type="text" name="username" [(ngModel)]="model.username" required>
<input type="email" name="email" [(ngModel)]="model.email" required email>
<input type="password" name="password" [(ngModel)]="model.password" required>
<button type="submit">Submit</button>
</form>
Features of Template Driven Forms:
- Simple to use: Template Driven form is an easy way to build forms in Angular. It is faster and easier to use. It makes use of directives to control the form state and value.
- Less component code: The logic related to form is present in the template itself. So there is less or no requirement to write logic related to form in the component file. So it is less complicated and easy to understand.
- Two-way data binding: In Template Driven form, we make use of two way data binding to control the input field. It make use of ngModel directive to bind the form input values and the component file.
- Easy Testing: Template Driven Forms are easier to test. We don't need to go any other place to test the logic. Since all the logic resides in the template form, testing is done in easy way and at single place.
- Template Driven Validation: The validation is done using the template. There is less or no requirement to write logic for the validation purpose in the component file. There are some in-built directives which are used for the validation of forms.
Example:
HTML
<!-- app.component.html -->
<form (ngSubmit)="onSubmit()">
<div>
<label for="username">Username:</label>
<input
type="text"
id="username"
name="username"
[(ngModel)]="userData.username"
required
/>
</div>
<div>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
[(ngModel)]="userData.email"
required
email
/>
</div>
<button type="submit">Submit</button>
</form>
JavaScript
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
userData = {
username: '',
email: '',
};
onSubmit() {
console.log(this.userData);
}
}
export class MyFormComponent { }
JavaScript
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';
@NgModule({
imports: [BrowserModule, FormsModule, ReactiveFormsModule],
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
providers: [],
})
export class AppModule { }
Output:

Aspect
| Reactive Forms
| Template Driven Forms
|
---|
Data Binding
| Data Binding is done using formControlName and formGroup.
| Data Binding is done using ngModel directive.
|
---|
Form Creation
| Form is created programmatically. We need to write more code in component.
| Form is created automatically from the template. There is less requirement to write code in component.
|
---|
Programming paradigm
| The logic of the form mainly resides in the template.
| The logic of the form is mainly defined in the template.
|
---|
Complexity Handling
| It is more suited for complex forms and dynamic form elements.
| It is more suitable for simpler forms.
|
---|
Validation
| The validation logic are defined in the component code.
| The validation is provided with the help of template directives.
|
---|
Flexibility
| There is more flexibility for handling complex and complicated usecases.
| There is less flexibility for handling complex and complicated usecases.
|
---|
Integration with backend
| It is easier to integrate with the backend.
| It is more difficult to integrate with the backend.
|
---|
Form Grouping
| There is proper grouping of form controls.
| There is no proper grouping of form controls.
|
---|
Conclusion
In Summary, we can conclude that there are two ways through which we can build forms in Angular. Template Driven forms is the easier and simplest method to build forms in Angular. It makes use of directives to control the component state and logic. While Reactive form is more complex way to build forms in Angular. It is used to build forms of more complex data management and logic.
Similar Reads
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. Template-Driven FormTemp
4 min read
How To Use Reactive Forms in Angular?
In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class. Core ComponentsFormGroup: Repres
5 min read
Difference between JSX vs Templates
JSX and Templates are two different things that are used by Javascript frameworks and libraries to show any content via DOM(Document Object Model). Nowadays there is a debate about using frameworks or libraries with JSX like ReactJs vs frameworks or libraries with Templates like VueJS. So there is a
5 min read
AWS CloudFormation Templates
CloudFormation is a popular Infrastructure as a code (Iac) tool provided by Amazon web services (AWS) that allows users to automate the provisioning of AWS services such as EC2, S3, Lamda, etc.CloudFormation manages the entire lifecycle of your infrastructure, including provisioning, updating, and d
11 min read
Building Complex Forms Using Angular Reactive Form
Imagine you are building a web page where you have to make a Form having fields, such as First Name, Last Name, and so on and you have to handle form inputs, validations, and interactions. Here, using Reactive Forms you define the structure of the form directly in Typescript code rather than HTML te
7 min read
Building Template-Driven Form in Angular
In Template Driven Forms we specify behaviors/validations using directives and attributes in our template and let it work behind the scenes. All things happen in Templates hence very little code is required in the component class. This is different from the reactive forms, where we define the logic
4 min read
React vs React Dom
React is a JavaScript library used for building user interfaces, especially for single-page applications. React DOM is a separate package that enables React to update and render UI components on the web browser by directly interacting with the browser's Document Object Model (DOM), ensuring smooth,
4 min read
Create A Template Driven Form In Angular
Template Driven Form in Angular means managing form input and validation primarily through HTML templates, using Angular directives like ngModel for two-way data binding and ngForm for form management. This approach is ideal for simpler forms where most of the logic and validation are handled direct
4 min read
Spectre Forms Inline Form
The Spectre Forms provide the most common control component used in a regular form. In this article, we will discuss the form inline forms. The form inline forms is an important component that can make any input field in a single line. Like In the previous articles we used radio, checkbox, etc they
1 min read
Server-Side Template Injection
SSTs (Server-Side Templates) facilitate easy dynamic HTML generation, but they are susceptible to SSTI attacks. While SSTs enhance webpage customization and performance by processing user information directly on the server, their vulnerability underscores the importance of robust security measures i
4 min read