Angular Template-Driven Forms


What are template-driven forms in Angular?

Template-driven forms in Angular are a way to create forms where most of the logic is written in the template (HTML) rather than in the component class. These forms rely on Angular's directives, such as ngModel, to handle data binding, validation, and form control. Template-driven forms are easy to implement and suitable for simpler forms with less complex logic.


How do you create a basic template-driven form in Angular?

To create a basic template-driven form in Angular, you need to import the FormsModule in your app's module and use the ngModel directive to bind form controls to component properties.

Steps to create a basic form:

  1. Import FormsModule in your module file.
  2. Use the ngModel directive in the template to bind input elements to component properties.
  3. Handle the form submission using the (ngSubmit) event.

Example of a basic template-driven form:

import { Component } from '@angular/core';

@Component({
  selector: 'app-contact-form',
  templateUrl: './contact-form.component.html'
})
export class ContactFormComponent {
  user = {
    name: '',
    email: ''
  };

  onSubmit() {
    console.log(this.user);
  }
}
<form #form="ngForm" (ngSubmit)="onSubmit()">
  <input type="text" name="name" [(ngModel)]="user.name" required />
  <input type="email" name="email" [(ngModel)]="user.email" required />
  <button type="submit">Submit</button>
</form>

In this example, the ngModel directive binds the name and email fields to the corresponding properties in the component. The form is submitted using the ngSubmit event, which calls the onSubmit method.


What is ngModel in template-driven forms, and how is it used?

ngModel is a directive in Angular that enables two-way data binding between form controls (such as input fields) and component properties. In template-driven forms, ngModel is used to track and manage form input values and synchronize them with the component's data model.

Example of using ngModel:

<input type="text" name="username" [(ngModel)]="user.username" />

In this example, the ngModel directive binds the input field to the username property in the component, enabling two-way data binding.


How do you handle form submission in template-driven forms?

Form submission in template-driven forms is handled by binding the form's (ngSubmit) event to a method in the component class. When the user submits the form, this method is called, and the form data is processed.

Example of handling form submission:

export class ContactFormComponent {
  user = {
    name: '',
    email: ''
  };

  onSubmit() {
    console.log('Form submitted:', this.user);
  }
}
<form (ngSubmit)="onSubmit()" #form="ngForm">
  <input type="text" name="name" [(ngModel)]="user.name" />
  <input type="email" name="email" [(ngModel)]="user.email" />
  <button type="submit">Submit</button>
</form>

In this example, the ngSubmit event triggers the onSubmit method in the component when the user submits the form.


How do you validate template-driven forms in Angular?

In template-driven forms, validation can be added using built-in Angular validators like required, minlength, maxlength, pattern, etc. These validators are added directly in the HTML using standard attributes, and Angular automatically tracks the form's validity.

Example of form validation:

<form #form="ngForm" (ngSubmit)="onSubmit()">
  <input type="text" name="name" [(ngModel)]="user.name" required minlength="3" #name="ngModel" />
  <div *ngIf="name.invalid && name.touched">Name is required and must be at least 3 characters long.</div>

  <input type="email" name="email" [(ngModel)]="user.email" required #email="ngModel" />
  <div *ngIf="email.invalid && email.touched">Valid email is required.</div>

  <button type="submit" [disabled]="form.invalid">Submit</button>
</form>

In this example, the required and minlength validators are applied to the input fields. The form displays error messages when the fields are invalid and disables the submit button if the form is not valid.


What is the role of #form="ngForm" in template-driven forms?

The template reference variable #form="ngForm" binds the form to the ngForm directive, which gives access to the form's properties, such as valid, invalid, and touched. This allows you to control the form's behavior, display validation messages, and conditionally disable form controls.

Example of using #form="ngForm":

<form #form="ngForm" (ngSubmit)="onSubmit()">
  <input type="text" name="username" [(ngModel)]="user.username" required />
  <button type="submit" [disabled]="form.invalid">Submit</button>
</form>

In this example, form.invalid is used to disable the submit button if the form is not valid.


How do you add custom validation to template-driven forms?

To add custom validation to template-driven forms, you can create a custom validator function in the component class and apply it using the [ngModelOptions] directive. Custom validators can be used to apply complex validation rules to form fields.

Example of custom validation:

export class ContactFormComponent {
  user = { email: '' };

  emailDomainValidator(control: NgModel) {
    const email = control.value;
    if (email && email.indexOf('@example.com') === -1) {
      return { emailDomain: true };
    }
    return null;
  }
}
<form (ngSubmit)="onSubmit()" #form="ngForm">
  <input type="email" name="email" [(ngModel)]="user.email" #email="ngModel" [ngModelOptions]="{ updateOn: 'blur' }" [ngModel]="user.email" [ngModelValid]="emailDomainValidator(email)" />
  <div *ngIf="email.errors?.emailDomain">Email must be from example.com domain.</div>

  <button type="submit">Submit</button>
</form>

In this example, the custom validator checks if the email domain is example.com, and if not, it shows a validation error.


How do you reset a form in Angular template-driven forms?

In Angular template-driven forms, you can reset the form using the reset() method. This clears all input values and resets the form state (such as touched and dirty statuses) to their initial values.

Example of resetting a form:

<form #form="ngForm" (ngSubmit)="onSubmit(form)">
  <input type="text" name="username" [(ngModel)]="user.username" />
  <button type="submit">Submit</button>
  <button type="button" (click)="form.reset()">Reset</button>
</form>

In this example, clicking the "Reset" button will clear the form fields and reset the form state.


How do you disable form controls in template-driven forms?

To disable form controls in template-driven forms, you can use the standard HTML disabled attribute, or conditionally disable controls based on component properties.

Example of disabling form controls:

<form (ngSubmit)="onSubmit()">
  <input type="text" name="username" [(ngModel)]="user.username" [disabled]="isDisabled" />
  <button type="submit">Submit</button>
</form>

In this example, the input field is conditionally disabled based on the value of the isDisabled property.

Ads