Site icon Blogs – Nexotips

Angular Forms: Template-Driven vs. Reactive With Best Understanding Example

Angular Form

There are two primary methods for creating forms with Angular Forms: template-driven forms and reactive forms. Every Angular Forms technique has a set of benefits and particular applications. The intricacy and specifications of your application will determine which of these Angular Form techniques is best for you. Reactive forms are ideal for more intricate and dynamic scenarios using Angular Form, whereas template-driven forms are ideal for simpler, more direct angular forms. You may choose the Angular Forms strategy that best fits the requirements of your project by being aware of the distinctions between these techniques.

Template-Driven Forms

Template-driven forms are the more traditional approach to form handling in Angular. In this approach, the form structure and validation rules are defined directly in the HTML template using Angular’s built-in directives like ngModel, ngForm, and ngSubmit.

Here’s a simple example of a template-driven form:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" [(ngModel)]="name" required>
    <div *ngIf="myForm.controls.name?.invalid && (myForm.controls.name?.dirty || myForm.controls.name?.touched)">
      Name is required.
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

In this example, the form structure and validation rules are defined directly in the HTML template. The ngModel directive is used to bind the input value to a component property, and the required attribute is used to add a validation rule.

The main advantages of template-driven forms are:

  1. Simplicity: Template-driven forms are relatively easy to set up and use, especially for simple forms.
  2. Familiarity: The syntax and approach are similar to AngularJS, making it easier for developers with AngularJS experience to transition to Angular.
  3. Automatic Form State Management: Angular handles the form state management (e.g., touched, dirty, valid) automatically, reducing the amount of boilerplate code you need to write.

However, template-driven forms also have some drawbacks:

  1. Limited Flexibility: As the form structure and validation rules are defined in the template, it can be more difficult to implement complex validation rules or dynamic form structures.
  2. Testability: Testing template-driven forms can be more challenging, as the form logic is spread across the template and the component class.
  3. Asynchronous Nature: Template-driven forms are asynchronous, which can make it more difficult to work with form data in a synchronous manner.

Reactive Forms

Reactive forms, on the other hand, take a more programmatic approach to form handling. In this approach, the form structure and validation rules are defined in the component class using Angular’s Reactive Forms API, which includes classes like FormGroup, FormControl, and FormArray.

Here’s an example of a reactive form:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.myForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="myForm.controls.name?.invalid && (myForm.controls.name?.dirty || myForm.controls.name?.touched)">
      Name is required.
    </div>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="myForm.controls.email?.invalid && (myForm.controls.email?.dirty || myForm.controls.email?.touched)">
      Email is required and must be valid.
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>

In this example, the form structure and validation rules are defined in the component class using the FormBuilder service. The formGroup and formControlName directives are used to bind the form controls to the HTML template.

The main advantages of reactive forms are:

  1. Flexibility: Reactive forms provide more flexibility in terms of implementing complex validation rules, dynamic form structures, and integrating with other asynchronous operations.
  2. Testability: Reactive forms are more testable, as the form logic is isolated in the component class and can be tested independently.
  3. Synchronous Nature: Reactive forms are synchronous, which makes it easier to work with form data in a synchronous manner.

However, reactive forms also have some drawbacks:

  1. Complexity: Reactive forms can be more complex to set up and use, especially for simple forms.
  2. Steeper Learning Curve: Developers need to be familiar with the Reactive Forms API and concepts like observables and RxJS to work effectively with reactive forms.

When to Use Template-Driven vs. Reactive Forms

The choice between template-driven and reactive forms depends on the complexity and requirements of your application:

Implementing Reactive Forms

To implement reactive forms in an Angular application, you’ll need to follow these steps:

  1. Import the ReactiveFormsModule: In your AppModule (or the module where you want to use reactive forms), import the ReactiveFormsModule from @angular/forms.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. Create a FormGroup in the Component Class: In your component class, create a FormGroup instance using the FormBuilder service.
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent {
  myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.myForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
  }
}
  1. Bind the FormGroup to the Template: In your component’s template, use the formGroup directive to bind the FormGroup instance to the form.
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" formControlName="name">
    <div *ngIf="myForm.controls.name?.invalid && (myForm.controls.name?.dirty || myForm.controls.name?.touched)">
      Name is required.
    </div>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email">
    <div *ngIf="myForm.controls.email?.invalid && (myForm.controls.email?.dirty || myForm.controls.email?.touched)">
      Email is required and must be valid.
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
  1. Handle Form Submission: In the component class, implement the onSubmit() method to handle the form submission.
onSubmit() {
  console.log(this.myForm.value);
}

This is a basic example of implementing a reactive form in Angular. You can further customize the form by adding more form controls, nested form groups, form arrays, and custom validators as needed.

Advantages of Reactive Forms

  1. Flexibility: Reactive forms provide more flexibility in terms of implementing complex validation rules, dynamic form structures, and integrating with other asynchronous operations.
  2. Testability: Reactive forms are more testable, as the form logic is isolated in the component class and can be tested independently.
  3. Synchronous Nature: Reactive forms are synchronous, which makes it easier to work with form data in a synchronous manner.
  4. Explicit Form Structure: The form structure is defined explicitly in the component class, making it easier to understand and maintain.
  5. Immutability and Predictability: Reactive forms are immutable, which means that each change in the form state returns a new state. This makes the form behavior more predictable and easier to reason about.

Disadvantages of Reactive Forms

  1. Complexity: Reactive forms can be more complex to set up and use, especially for simple forms.
  2. Steeper Learning Curve: Developers need to be familiar with the Reactive Forms API and concepts like observables and RxJS to work effectively with reactive forms.
  3. More Boilerplate Code: Reactive forms require more boilerplate code to set up the form structure and validation rules in the component class.

Angular Form Conclusion

Both template-driven and reactive forms have their own strengths and weaknesses. The choice between them depends on the complexity and requirements of your Angular application. For simple forms, template-driven forms may be a better choice, while for complex forms, reactive forms are generally the recommended approach. Understanding the differences between the two and when to use each one will help you make the right decision for your project.

Read More : Angular Material Grid-List, Side Nav, And Navbar With Best Example

Exit mobile version