Open In App

Reactive Forms vs Template Driven Forms

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

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:

Reactive Forms

After Submitting Button is clicked

Template Driven Forms

Template 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:

Template Driven Forms

Difference between Reactive Forms and Template Driven Forms

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads