Template Driven Forms And Validation In Angular With TypeScript

This article will give you extensive information on Template Driven Forms and how to create a form with Template Driven Forms approach, as well as how to implement validation with Template Driven Forms with Angular 6 and TypeScript.

Forms are useful when you need to gather information from the user. They provide an interface from where a user can fill in all required details and validate the information before submitting the data. Validation is not only required for checking the required data but also to use for checking patterns of data. When talking about form and validation in Angular, we have two different ways to create forms, the first one is the Template Driven Forms and another one is Reactive Forms. Today we only focus on Template Driven Form and learn what it is and why we should use it. Apart from this, we will also learn how to create Template Driven Forms along with validations. 

So, let's first understand what Template Driven Forms are and what are the reasons to use them. 

TEMPLATE DRIVEN FORMS

As the name suggests, in this approach to create forms, we focus on template instead of component code. We add the template with different types of controls like input, dropdown, checkbox etc., and bind directive with them to handle the behavior of template. It is not a new approach, however, we have also used this approach in Angular JS. This is a similar way to create a form using ngModel and two-way data-binding as we did in Angular JS. In Template Driven Forms, validations are implemented using HTML 5 attributes like required, minLength, maxLength, pattern etc. This is not very complex while implementing, it is very easy to use. We cannot use Template Driven Forms approach to create forms in each scenario, this is only feasible for those scenarios where form structure is simple.

If you are willing to write test cases for the app then don't use this approach, since with the Template Driven Forms, testing the form is not easy. Another point I would like to mention here is that due to so many codes in Template sides, it creates the complexity to understand template codes and create readability issues. 

CREATE ANGULAR PROJECT

Now let's move forward to a practical demonstration and step by step understanding of how to create Template Driven Forms and implement validation with that. So, we are going to create an Angular project [For this demonstration, we are using Angular version 6]. You can follow the below steps to create a new Angular 6 CLI project. 

  1. Open Visual Studio Code and press CTRL + ~ to open a terminal window.
  2. Move to the particular directory where the project needs to be created.
  3. To create a new Angular CLI project, type command ng new FormValidationDemo --routing and press Enter.
  4. Execute command npm install bootstrap@3 to add bootstrap with the project.
  5. Now we have project ready, now move to that project folder and run the project using a command as  ng serve --open

For more about how to create an Angular CLI project with step by step instructions, please follow this article,

MORE ARTICLES ON ANGULAR WHICH YOU MAY LIKE.

IMPLEMENTATION OF TEMPLATE DRIVEN FORMS

Before moving to the next step, first, we will configure Bootstrap, so that we can use the bootstrap classes. So, open styles.css and add the  following code which is responsible for importing bootstrap CSS from installed node packages.

  1. @import "node_modules/bootstrap/dist/css/bootstrap.min.css";  
  2. .invalid-data {  
  3.     border: 2px solid red;  
  4. }  
  5.   
  6. .valid-data {  
  7.     border: 2px solid rgb(19, 92, 4);  
  8. }  

To implement the Template Driven Forms with an Angular project, we first need to add a module which is essential for providing all the required components of the Template Driven Form. So, open the app.mdoule.ts and add the FormsModule imported from @angular/forms. A point to note here is that FormsModule is used for creating Template Driven Forms and ReactiveFormsModule is used for created Reactive Forms.

After that, we will add one component as the name 'TemplateDrivenFormComponent' where we will create a form and validation with that. To add a new component, move to app folder in terminal windows and type the command as follows.

ng g c TemplateDrivenForm

So, now we have component ready. Let's confirm the route to reach with this component.

  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { TemplateDrivenFormComponent } from 'src/app/template-driven-form/template-driven-form.component';  
  4.   
  5. const routes: Routes = [    
  6.   {  
  7.     path: 'templateform',  
  8.     pathMatch: 'full',  
  9.     component: TemplateDrivenFormComponent  
  10.   }  
  11. ];  
  12.   
  13. @NgModule({  
  14.   imports: [RouterModule.forRoot(routes)],  
  15.   exports: [RouterModule]  
  16. })  
  17. export class AppRoutingModule { }  

Now, let's create a simple form using bootstrap classes where the user can enter his/her address details. So, just open the 'template-driven-form.component.html' and add the following HTML code. 

  1. <div class="row">  
  2.   <div class="col-md-4 col-md-offset-4" style="margin-top: 50px; border: 1px solid rgb(100, 98, 98); padding: 30px;">  
  3.     <form class="form-horizontal" role="form">  
  4.       <fieldset>  
  5.         <legend>Address Details:  
  6.           <strong>Template Driven Form</strong>  
  7.         </legend>  
  8.   
  9.         <div class="form-group">  
  10.           <label class="col-sm-2 control-label" for="textinput">Address</label>  
  11.           <div class="col-sm-10">  
  12.             <input type="text" name="address" placeholder="Enter Address" class="form-control">  
  13.           </div>  
  14.         </div>  
  15.   
  16.         <div class="form-group">  
  17.           <label class="col-sm-2 control-label" for="textinput">City</label>  
  18.           <div class="col-sm-10">  
  19.             <input type="text" name="city" placeholder="Enter City Name" class="form-control">  
  20.           </div>  
  21.         </div>  
  22.   
  23.         <div class="form-group">  
  24.           <label class="col-sm-2 control-label" for="textinput">State</label>  
  25.           <div class="col-sm-4">  
  26.             <input type="text" name="state" placeholder="State" class="form-control">  
  27.           </div>  
  28.   
  29.           <label class="col-sm-2 control-label" for="textinput">Postcode</label>  
  30.           <div class="col-sm-4">  
  31.             <input type="text" name="postcode" placeholder="Enter Post Code" class="form-control">  
  32.           </div>  
  33.         </div>  
  34.   
  35.         <div class="form-group">  
  36.           <label class="col-sm-2 control-label" for="textinput">Country</label>  
  37.           <div class="col-sm-10">  
  38.             <select class="form-control" name="country">  
  39.               <option>---Select---</option>  
  40.               <option *ngFor="let item of countryData" [value]="item">  
  41.                 {{item}}  
  42.               </option>  
  43.             </select>  
  44.           </div>  
  45.         </div>  
  46.   
  47.         <div class="form-group">  
  48.           <div class="col-sm-2 form-check">  
  49.             <input type="checkbox" name="aggrement" class="form-check-input">  
  50.           </div>  
  51.           <label class="col-sm-10 form-check-label">I aggree to Terms & Conditions  
  52.           </label>  
  53.         </div>  
  54.   
  55.         <div class="form-group">  
  56.           <div class="col-sm-12">  
  57.             <span style="color: red;">Please Aggree with Terms & Conditions.</span>  
  58.           </div>  
  59.         </div>  
  60.   
  61.         <div class="form-group">  
  62.           <div class="col-sm-offset-2 col-sm-10">  
  63.             <div class="pull-right">  
  64.               <button type="submit" class="btn btn-primary" style="margin: 4px;">Save</button>  
  65.               <button type="reset" class="btn btn-default">Reset</button>  
  66.             </div>  
  67.           </div>  
  68.         </div>  
  69.       </fieldset>  
  70.     </form>  
  71.   </div>  
  72. </div>  

First, let us see what will be the output of the above template. So, run the app usig ng serve command. Now see the output. You will find the output as follows. Here, we are going to create an Address form which has an address, city, state, and postcode as an Input field and country as a drop-down field. Apart from this, we have one checkbox for validating the terms and conditions. We will try to validate almost every control, either input control or dropdown. Form validation will happen on the form's submission.

Template Driven Forms And Validation In Angular With Typescript

The above form is a simple form and before converting the above simple form to Template Driven Forms, we will create a Model as follows. 

  1. export interface addressModel{  
  2.     address: string,  
  3.     city: string,  
  4.     state: string,  
  5.     postcode: number,  
  6.     country: any[],  
  7.     aggrement: boolean  
  8. }  

Now, let's modify the 'template-driven-form.component.ts' file as follows. Here we first construct the data for Country drop-down and construct a model with a type of addressModel with their default values. We have also defined one method as onFormSubmit() which will be called when we will submit the form. We are using console.log() for now to print the data in console window of the browser.

  1. import { Component, OnInit } from '@angular/core';  
  2. import { addressModel } from 'src/app/data/address.model';  
  3.   
  4. @Component({  
  5.   selector: 'app-template-driven-form',  
  6.   templateUrl: './template-driven-form.component.html',  
  7.   styleUrls: ['./template-driven-form.component.css']  
  8. })  
  9. export class TemplateDrivenFormComponent implements OnInit {  
  10.   
  11.   countryData: any[] = ['India''US''UK'];  
  12.   
  13.   model: addressModel = {  
  14.     address: '',  
  15.     city: '',  
  16.     state:'',  
  17.     postcode: null,  
  18.     country: null,  
  19.     aggrement: false  
  20.   };  
  21.   
  22.   constructor() { }  
  23.   
  24.   ngOnInit() {  
  25.   }  
  26.   
  27.   onFormSubmit() {  
  28.     console.log("Full Address"this.model);    
  29.   }  
  30. }  

Now, its time to understand what are the attributes available from HTML 5 which can be used to validate the forms and these attributes are as follows. 

  • required - Value is required.
  • minlength - The minimum characters are required as a value.
  • maxlength - The maximum characters are required as a value.
  • pattern - The value should match the pattern.

In Angular, we can validate HTML controls as well as forms. There are different attributes available to validate form's control which return true or false.

  • untouched - The control is not touched yet.
  • touched - The control is touched.
  • pristine - The control's value is not modified or changed yet.
  • dirty - The control's value is modified or changed.
  • invalid - The control's value is not valid.
  • valid - The control's value is valid.

We can validate Form also using the following attributes.

  • pristine - Not any control's value has modified yet.
  • dirty - Some or all control's values have modified yet.
  • invalid - Form is not valid since control value is not valid.
  • valid - Form is valid.
  • submitted - The form has submitted.

Now, let's change the above template one by one to implement Template Driven Forms along with validation.

First, let's modify the form tag as follows, here you can see we are creating the instance of ngForm directive and defining ngSubmit event, which will call onFormSubmit() method once form will be valid. 

  1. <form class="form-horizontal" role="form" #f="ngForm" (ngSubmit)="f.form.valid && onFormSubmit()">  

As per the Angular.IO.

The NgForm directive supplements the form element with additional features. It holds the controls you created for the elements with an ngModel directive and name attribute, and monitors their properties, including their validity. It also has its own valid property which is true only if every contained control is valid.

The #f is the reference variable to the form directive. Using this, we can handle the behavior of the forms.

Now let's modify the template for Input control. First, we will use [(ngModel)] to use two-way data binding with model data. After that, we will add CSS class which changes the color of the control on being valid or invalid while submitting the form. Next, add the HTML 5 attribute required to make value compulsory for that control. Next is a very important point, here we will add ngModel directive with the name of the control along with the prefix of #.

Here #address="ngModel" exports NgModel into a local variable called name. NgModel mirrors many of the properties of its underlying FormControl instance, so you can use this in the template to check for control states such as valid and dirty. You can also add validation using touched or untouched.

  1. <input type="text" [(ngModel)]="model.address" [ngClass]="{'invalid-data': address.invalid && f.submitted, 'valid-data': address.valid && f.submitted}"  
  2.               required name="address" #address="ngModel" placeholder="Enter Address" class="form-control">  
  3.   
  4. <div *ngIf="address.invalid && f.submitted">  
  5.    <span style="color: red;">Please Enter Address.</span>  
  6. </div  

As per the above guidelines which we have implemented with the Input control, we will follow for Dropdown and Checkbox as well respectively.

  1. <div class="col-sm-10">  
  2.   <select class="form-control" name="country" [(ngModel)]="model.country" #country="ngModel" [ngClass]="{'invalid-data': country.invalid && f.submitted, 'valid-data': country.valid && f.submitted}" required>  
  3.     <option [ngValue]="null">---Select---</option>  
  4.     <option *ngFor="let item of countryData" [value]="item">  
  5.       {{item}}  
  6.     </option>  
  7.   </select>  
  8.   
  9.   <div *ngIf="country.invalid && f.submitted">  
  10.     <span style="color: red;">Please Select Country.</span>  
  11.   </div>  
  12. </div>  

Checkbox validation is as follows.

  1. <div class="form-group">  
  2.    <div class="col-sm-2 form-check">  
  3.      <input type="checkbox" [(ngModel)]="model.aggrement" [ngClass]="{'invalid-data': aggrement.invalid && f.submitted, 'valid-data': aggrement.valid && f.submitted}" required name="aggrement" #aggrement="ngModel" class="form-check-input">  
  4.   </div>  
  5.   <label class="col-sm-10 form-check-label">I aggree to Terms & Conditions  
  6.   </label>  
  7. </div>  

We can change form code similar to the following code to make it Template Driven Forms along with validation implementations.

  1. <div class="row">  
  2.   <div class="col-md-4 col-md-offset-4" style="margin-top: 50px; border: 1px solid rgb(100, 98, 98); padding: 30px;">  
  3.     <form class="form-horizontal" role="form" #f="ngForm" (ngSubmit)="f.form.valid && onFormSubmit()">  
  4.       <fieldset>  
  5.         <legend>Address Details:  
  6.           <strong>Template Driven Form</strong>  
  7.         </legend>  
  8.   
  9.         <div class="form-group">  
  10.           <label class="col-sm-2 control-label" for="textinput">Address</label>  
  11.           <div class="col-sm-10">  
  12.             <input type="text" [(ngModel)]="model.address" [ngClass]="{'invalid-data': address.invalid && f.submitted, 'valid-data': address.valid && f.submitted}"  
  13.               required name="address" #address="ngModel" placeholder="Enter Address" class="form-control">  
  14.   
  15.             <div *ngIf="address.invalid && f.submitted">  
  16.               <span style="color: red;">Please Enter Address.</span>  
  17.             </div>  
  18.   
  19.           </div>  
  20.         </div>  
  21.   
  22.         <div class="form-group">  
  23.           <label class="col-sm-2 control-label" for="textinput">City</label>  
  24.           <div class="col-sm-10">  
  25.             <input type="text" [(ngModel)]="model.city" [ngClass]="{'invalid-data': city.invalid && f.submitted, 'valid-data': city.valid && f.submitted}"  
  26.               required name="city" #city="ngModel" placeholder="Enter City Name" class="form-control">  
  27.   
  28.             <div *ngIf="city.invalid && f.submitted">  
  29.               <span style="color: red;">Please Enter City.</span>  
  30.             </div>  
  31.           </div>  
  32.         </div>  
  33.   
  34.         <div class="form-group">  
  35.           <label class="col-sm-2 control-label" for="textinput">State</label>  
  36.           <div class="col-sm-4">  
  37.             <input type="text" [(ngModel)]="model.state" name="state" placeholder="State" class="form-control">  
  38.           </div>  
  39.   
  40.           <label class="col-sm-2 control-label" for="textinput">Postcode</label>  
  41.           <div class="col-sm-4">  
  42.             <input type="text" [(ngModel)]="model.postcode" [ngClass]="{'invalid-data': postcode.invalid && f.submitted, 'valid-data': postcode.valid && f.submitted}"  
  43.               required name="postcode" #postcode="ngModel" placeholder="Enter Post Code" class="form-control">  
  44.   
  45.             <div *ngIf="postcode.invalid && f.submitted">  
  46.               <span style="color: red;">Please Enter Valid Post Code.</span>  
  47.             </div>  
  48.           </div>  
  49.         </div>  
  50.   
  51.         <div class="form-group">  
  52.           <label class="col-sm-2 control-label" for="textinput">Country</label>  
  53.           <div class="col-sm-10">  
  54.             <select class="form-control" name="country" [(ngModel)]="model.country" #country="ngModel" [ngClass]="{'invalid-data': country.invalid && f.submitted, 'valid-data': country.valid && f.submitted}"  
  55.               required>  
  56.               <option [ngValue]="null">---Select---</option>  
  57.               <option *ngFor="let item of countryData" [value]="item">  
  58.                 {{item}}  
  59.               </option>  
  60.             </select>  
  61.   
  62.             <div *ngIf="country.invalid && f.submitted">  
  63.               <span style="color: red;">Please Select Country.</span>  
  64.             </div>  
  65.           </div>  
  66.         </div>  
  67.   
  68.         <div class="form-group">  
  69.           <div class="col-sm-2 form-check">  
  70.             <input type="checkbox" [(ngModel)]="model.aggrement" [ngClass]="{'invalid-data': aggrement.invalid && f.submitted, 'valid-data': aggrement.valid && f.submitted}"  
  71.               required name="aggrement" #aggrement="ngModel" class="form-check-input">  
  72.           </div>  
  73.           <label class="col-sm-10 form-check-label">I aggree to Terms & Conditions  
  74.           </label>  
  75.         </div>  
  76.   
  77.         <div class="form-group">  
  78.           <div class="col-sm-12" *ngIf="aggrement.invalid && f.submitted">  
  79.             <span style="color: red;">Please Aggree with Terms & Conditions.</span>  
  80.           </div>  
  81.         </div>  
  82.   
  83.         <div class="form-group">  
  84.           <div class="col-sm-offset-2 col-sm-10">  
  85.             <div class="pull-right">  
  86.               <button type="submit" class="btn btn-primary" style="margin: 4px;">Save</button>  
  87.               <button type="reset" class="btn btn-default">Reset</button>  
  88.             </div>  
  89.           </div>  
  90.         </div>  
  91.       </fieldset>  
  92.     </form>  
  93.   </div>  
  94. </div>  

So, we have finished converting a simple form to Template Driven Forms along with validation with each control. Let's run the project and see the output. Once we will run the project and click to Save button, all required field borders will be in red. If we fill in the valid value for that control, it will become green. 

Template Driven Forms And Validation In Angular With Typescript

Conclusion

So, today we learned about Template Driven Forms in Angular and how to create and implement validation with them using TypeScript.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks.


Similar Articles