Angular 13 Template Driven Form Validation Example

Angular Template-driven Form validation tutorial, this comprehensive guide helps you find out how to add validation in angular template-driven forms.

We will share with you perfect ways to create a basic user form with ngModel directive; not just that, you will also ascertain how to integrate validation in angular using built-in validation techniques.

The NgModel is a fundamental directive for creating user-friendly forms with the template-driven approach; it creates a FormControl instance from a domain model and connects with a form control element.

The FormControl instance traces the value, user interaction, and validation state of the control and keeps the view synced and intact with the model. Throughout this tutorial, you will see how to use ngModel within a form to create and validate form values.

Angular 13 Template-driven Form Validation Example

  • Install Angular App
  • Install Bootstrap Package
  • Register Forms Module
  • Build Template Driven Form with Bootstrap UI
  • Implement Validation in Template-driven Form
  • Start Development Server

Install Angular App

You have to make sure that you have installed the Angular CLI globally on your system:

npm install -g @angular/cli

Next, run command for starting the angular app installation:

ng new ng-form-validaiton

Get inside the project folder:

cd ng-form-validaiton

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Install Bootstrap Package

In this step, you have to install Bootstrap package in angular using following command:

npm i bootstrap

Define Bootstrap CSS path in angular.json:

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
         ]

Register Forms Module in AppModule

In this step, you need to import FormsModule from the @angular/forms package and register within the NgModule’s imports array:

Open app.module.ts file, similarly update the below code:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Build Template Driven Form with Bootstrap UI

Open app.component.html file, likewise add the following code:

<div class="container mt-5" style="max-width: 550px;">

  <form #myForm="ngForm" (ngSubmit)="submit(myForm)">
    <div class="form-group">
      <label>Name</label>
      <input type="text" class="form-control" name="name" [(ngModel)]="model.name" required>
    </div>

    <div class="form-group">
      <label>Email</label>
      <input type="email" class="form-control" name="email" [(ngModel)]="model.email" required>
    </div>

    <div class="form-group">
      <label>Password</label>
      <input type="password" class="form-control" name="password" [(ngModel)]="model.password" required>
    </div>

    <div class="form-group">
      <label>Subjects</label>
      <select class="form-control" name="subjects" [(ngModel)]="subjects">
        <option value="">Choose value</option>
        <option *ngFor="let subject of Subjects" [value]="subject">
          {{subject}}
        </option>
      </select>
    </div>

    <div class="form-group">
      <button class="btn btn-primary btn-block">Submit</button>
    </div>
  </form>

</div>

To get access to the template-driven form, define the form tag with template reference variable #myForm.

Add [(ngModel)] binding for every property followed by name attribute; the ngModel now enable the two-way data binding for the form object.

Additionally, we created the template-driven select dropdown form element with dynamic values.

Open app.component.ts file, similarly insert the following code:

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

export class Student {
  public name: string;
  public email: string;
  public password: string;
  public subjects: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  model = new Student();

  Subjects: string[] = [
    'Science',
    'Math',
    'Physics',
    'Finance'
  ];

  constructor() { }

  submit(data) {
    console.log(data.value)
  }
}

The sample application form defines the Student class, which manifests the data model exhibited in the form.

Create the model instance from the Student class.

The Subjects array holds the dynamic properties for the angular select drop-down element.

Print the form values on the form submit in the console.

Create Template Driven Form with Bootstrap UI

Implement Validation in Template-driven Form

Open app.component.html file, additionally place the following code within:

<div class="container mt-5" style="max-width: 550px;">

  <form #myForm="ngForm" (ngSubmit)="submit(myForm)">
    <div class="form-group">
      <label>Name</label>
      <input 
        type="text" 
        class="form-control" 
        name="name" 
        [(ngModel)]="model.name" 
        #name="ngModel" 
        [ngClass]="{ 'is-invalid': myForm.submitted && name.invalid }"
        required>

      <!-- Error -->
      <div class="text-danger mt-1" *ngIf="myForm.submitted && name.invalid">
        <p *ngIf="name.errors.required">Name value is required.</p>
      </div>
    </div>

    <div class="form-group">
      <label>Email</label>
      <input 
        type="email" 
        class="form-control" 
        name="email" 
        [(ngModel)]="model.email" 
        #email="ngModel" 
        [ngClass]="{ 'is-invalid': myForm.submitted && email.invalid }"        
        required>

      <!-- Error -->
      <div *ngIf="myForm.submitted && email.invalid" class="invalid-feedback">
        <div *ngIf="email.errors.required">Email is required.</div>
        <div *ngIf="email.errors.email">Please provide valid email.</div>
      </div>
    </div>

    <div class="form-group">
      <label>Password</label>
      <input 
        type="password" 
        class="form-control" 
        name="password" 
        [(ngModel)]="model.password" 
        #password="ngModel"
        [ngClass]="{ 'is-invalid': myForm.submitted && password.invalid }" 
        minlength="6"
        required>

        <!-- Error -->
        <div *ngIf="myForm.submitted && password.invalid" class="invalid-feedback">
          <div *ngIf="password.errors.required">Set a strong password.</div>
          <div *ngIf="password.errors.minlength">Minimum 6 characters required.</div>
        </div>        
    </div>

    <div class="form-group">
      <label>Subjects</label>
      <select class="form-control" name="subjects" [(ngModel)]="subjects">
        <option value="">Choose value</option>
        <option *ngFor="let subject of Subjects" [value]="subject">
          {{subject}}
        </option>
      </select>
    </div>

    <div class="form-group">
      <button class="btn btn-primary btn-block">Submit</button>
    </div>
  </form>

</div>

Start Development Server

Next, you need to test the angular form validation, So run angular development server:

ng serve

Open browser, enter the below url in address bar and hit enter:

http://localhost:4200

Angular Template Driven Form Validation Example

Conclusion

Ultimately, this extensive guide is completed; throughout this tutorial, we created a simple user signup form using the template driven approach in angular application.

You saw how simple it is to add validation within the angular template. Equally important, you learned to use bootstrap UI to build an angular form.