NashTech Blog

Table of Contents
people working on macbooks sitting by the window
angular-forms-logo

Forms are an essential part of any web application. They provide a means for users to interact with your application by inputting data, making selections, and submitting information. Angular forms and validation is based on two main building blocks: Template-driven forms and Reactive forms (also known as Model-driven forms). These two approaches offer different levels of control and flexibility depending on your application’s requirements.

Template-Driven Angular Forms

Template-driven forms are more suitable for simple forms with basic validation requirements. They are called “template-driven” because the form structure and validation rules are defined directly in the HTML template using Angular template syntax.

Benefits of Template-Driven Forms

  • Rapid Development: They are quick to set up and are well-suited for simple forms, making them an excellent choice for prototypes or small-scale applications.
  • Easy to Understand: Template-Driven Forms closely resemble traditional HTML forms, making them intuitive for developers who are familiar with HTML.
  • Built-In Validation: Angular provides built-in validation directives for common use cases, reducing the need for custom validation logic.
  • Two-Way Data Binding: [(ngModel)] allows for seamless synchronization between form controls and component properties.

Limitations of Template-Driven Forms

While Template-Driven Forms are great for simple forms, they may not be the best choice for complex scenarios. Here are some limitations:

  • Limited Programmatic Control: With Template-Driven Forms, the majority of the form logic is in the template, making it challenging to perform complex form manipulation programmatically.
  • Limited Reusability: Reusing form logic across multiple components can be cumbersome.
  • Testing Complexity: Unit testing can be more challenging because some form logic is in the template.

Reactive Forms (Model-Driven Forms) in Angular

Reactive Forms, often referred to as Model-Driven Forms, are a more programmatic and flexible approach to building forms compared to Template-Driven Forms. In Reactive Forms, you define the form structure and validation rules programmatically within your Angular component.

Reactive Forms offer several advantages:

  • Full Programmatic Control: Reactive Forms provide extensive control and flexibility to define complex validation rules and dynamic form behaviors programmatically.
  • Reusable Form Logic: You can create custom form controls and reuse them across different components, promoting code reusability.
  • Simplified Unit Testing: Since the form logic resides in the component, unit testing is more straightforward, and you have better control over testing scenarios.
  • Dynamic Forms: Reactive Forms allow you to dynamically add or remove form controls and adjust validation rules based on user interactions.

Limitations of Reactive Forms

While Reactive Forms are powerful, they come with a steeper learning curve and might be overkill for simple forms. Consider these limitations:

  • More Code: Building forms programmatically requires more code compared to Template-Driven Forms, which can be less verbose.
  • Complexity: For small and straightforward forms, Reactive Forms might introduce unnecessary complexity.
  • Learning Curve: Developers who are new to Angular might find Reactive Forms more challenging to grasp initially.

Getting Started with Reactive Forms in Angular Forms

To start building forms with Reactive Forms in Angular, follow these steps:

Step 1: import the modules:

In your Angular component, import the necessary modules:

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

Step-2: Define the Form Model:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      name: ['', [Validators.required, Validators.minLength(3)]],
      email: ['', [Validators.required, Validators.email]],
      age: [null, [Validators.required, Validators.min(18)]],
    });
  }
}

In this example, we use the FormBuilder service to create the form controls and define validation rules.

Step 3: Bind Form Controls in the Template:

In your component’s template (usually in the app.component.html file), bind the form controls to HTML input elements using formControlName:

 <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
      <label for="exampleInputPassword1">Name</label>
      <input type="text" formControlName="name" class="form-control" id="exampleInputName" placeholder="Enter name">
      <div *ngIf="form.get('name')?.invalid && (form.get('name')?.dirty || form.get('name')?.touched)">
        <small class="text-danger" *ngIf="form.get('name')?.hasError('required')">Name is required.</small>
        <small class="text-danger" *ngIf="form.get('name')?.hasError('minlength')">Name should be at least 3 characters.</small>
      </div>
    </div>
    <div class="form-group">
      <label for="exampleInputEmail1">Email address</label>
      <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" formControlName="email">
      <div *ngIf="form.get('email')?.invalid && (form.get('email')?.dirty || form.get('email')?.touched)">
        <small class="text-danger" *ngIf="form.get('email')?.hasError('required')">Email is required.</small>
        <small class="text-danger" *ngIf="form.get('email')?.hasError('email')">Invalid email format.</small>
      </div>
    </div>
    <div class="form-group">
      <label>Age</label>
      <input type="number" formControlName="age"class="form-control" id="exampleInputname"  placeholder="Enter email">
      <div *ngIf="form.get('age')?.invalid && (form.get('age')?.dirty || form.get('age')?.touched)">
        <small class="text-danger" *ngIf="form.get('age')?.hasError('required')">Age is required.</small>
        <small class="text-danger" *ngIf="form.get('age')?.hasError('min')">Age must be at least 18.</small>
      </div>
    </div>
    <button type="submit" class="btn btn-primary" [disabled]="form.invalid">Submit</button>
  </form>

Step 4: Handle Form Submission

Define a method in your component that handles the form submission. In this example, we have an onSubmit() method that you can customize to perform actions like sending data to a server, displaying messages, or navigating to a different page.

  onSubmit() {
    if (this.form.valid) {
      // Form is valid, do something with the data
      console.log(this.form.value);
    }
  }

Conclusion

Reactive Forms (Model-Driven Forms) in Angular provide a powerful and flexible way to build forms for your web applications. They are well-suited for complex forms with advanced validation and dynamic behaviors, offering full programmatic control and code reusability. Template-Driven Forms in Angular provide a straightforward and efficient way to build forms for your web applications.

Picture of Aasif Ali

Aasif Ali

Aasif Ali is a Software Consultant at NashTech. He is proficient in various programming languages like Java, Python, PHP, JavaScript, MySQL, and various frameworks like Spring/Springboot, .Net. He is passionate about web development and curious to learn new technologies. He is a quick learner, problem solver and always enjoy to help others. His hobbies are watching Sci-fi movies , Playing badminton and listening to songs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top