Template Driven Form In Angular 11

Introduction

 
In this article, I am going to tell you how to implement Template Driven Form in the Angular 11 project. In this article, I am covering how to  create projects, implement template-driven forms, get forms data, set data in form and validation.
 
In this article, I’m using bootstrap for designing forms so if you do not know how to add bootstrap in Angular 11 then please refer to the below article first.
In This Article,:
  • Create new project
  • Create Simple Form Design
  • Make Form Template Driven Form
  • Get form Data with the name attribute
  • Get Data using Local Variable
  • Set Data in Form
  • Validation in Form

Create New Project

 
On my pc, there is already Angular’s latest version installed. If you do not have angular in your system you can install it in a few steps. You can refer to angular’s official website to learn how to install angular.
 
Run the following command to create a new Angular project. Here ng means Angular, new determine that create a new project and FormsInAngular is the project name. 
  1. ng new FormsInAngular  
After running this command you will ask some questions about add routing and which style sheet you want to use in your project. You can choose as per your requirement.
 
Template Driven Form In Angular 11
 

Create Simple Form Design

 
Create a form as per your requirement here I create a form that has textbox, dropdown, and checkbox.
  1. <div class="row mt-1">    
  2.     
  3.   <form>    
  4.     <div class="form-group  col-6 m-2 p-2">    
  5.       <label for="inputAddress2">Name</label>    
  6.       <input type="text" class="form-control"  name="name" id="name" placeholder="Name"  >    
  7.     </div>    
  8.     <div class="form-group col-6 m-2 p-2">    
  9.       <label for="inputEmail4">Email</label>    
  10.       <input type="email" class="form-control" id="email" name="email" placeholder="Email"  >    
  11.     </div>    
  12.     <div class="form-group col-6 m-2 p-2">    
  13.       <label for="inputPassword4">Password</label>    
  14.       <input type="password" class="form-control" id="password"  name="password" placeholder="Password"  >    
  15.     </div>    
  16.     
  17.     <div class="form-group  col-6 m-2 p-2">    
  18.       <label for="inputAddress">Address</label>    
  19.       <input type="text" class="form-control" name="address" id="address" placeholder="1234 Main St"  >    
  20.     </div>    
  21.     
  22.     
  23.     <div class="form-group col-6 m-2 p-2">    
  24.       <label for="inputCity">City</label>    
  25.       <input type="text" class="form-control" id="city" name="city"  >    
  26.     </div>    
  27.     <div class="form-group col-4 m-2 p-2">    
  28.       <label for="state">State</label>    
  29.       <select id="state" name="state" class="form-control"  >    
  30.         <option selected>Choose...</option>    
  31.         <option>Gujarat</option>    
  32.         <option>UP</option>    
  33.         <option>Delhi</option>    
  34.       </select>    
  35.     </div>    
  36.     
  37.       <div class="form-group col-3 m-2 p-2">    
  38.         <label for="inputZip">Zip</label>    
  39.         <input type="text" class="form-control" id="zip" name="zip"  >    
  40.       </div>    
  41.     <div class="form-group m-2 p-2">    
  42.       <div class="form-check">    
  43.         <input class="form-check-input" type="checkbox" id="isMarried" name="isMarried"  >    
  44.         <label class="form-check-label" for="isMarried">    
  45.           Married    
  46.         </label>    
  47.       </div>    
  48.     </div>    
  49.     <button type="submit" class="btn btn-primary m-2 p-2">Submit Form</button>    
  50.   </form>    
  51. </div>     

Make Form Template Driven Form

 
Step 1
 
Add FormsModule in your Module import array. For using forms in Angular we need to import this.
  1. import { FormsModule } from '@angular/forms';  // Import this module for use forms  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { NgModule } from '@angular/core';   
  4. import { AppComponent } from './app.component';  
  5.   
  6. @NgModule({  
  7.   declarations: [  
  8.     AppComponent  
  9.   ],  
  10.   imports: [  
  11.     BrowserModule,  
  12.     FormsModule                    // Add this module for use forms  
  13.   ],  
  14.   providers: [],  
  15.   bootstrap: [AppComponent]  
  16. })  
  17. export class AppModule { }  
Step 2
 
Assign your form as ngForm as below give your form name using # and assign ngForm to it. Now your form is treated as template-driven form.
  1. <form #DemoForm="ngForm"></form>  

Get form Data with name attribute

 
Step 1
 
Add ngModel attribute in an element. 
 
Step 2
 
As you see in the above form design that we are given name attribute to every element because if we are using ngModel and not given name attribute that it gives an error like below. So if you do not need to give a name to your element give it.
 
Template Driven Form In Angular 11
 
Step 3
 
Add submit event in form and call that function which we will create in .ts file and pass your form name without # in the parameter.
  1. <form #DemoForm="ngForm" (ngSubmit)="onSubmit(DemoForm)">  
Step 4
 
Create a function in .ts file to show data that takes one parameter form. You can get the value of form in an object with property same as your name given in name attribute. For value use YourFormParament.value .
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.scss']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'FormsInAngular';  
  10.     
  11.   onSubmit(DemoForm){  
  12.     console.log(DemoForm.value);  
  13.   }  
  14. }  

Output
 
Template Driven Form In Angular 11
 

Get Data using Local Variable

 
We can also use local variables or objects for getting data from the form. Here we define some variables in .ts file and use them in form. Here are ts file changes.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.scss']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'FormsInAngular';  
  10.   
  11.   name: string = "";  
  12.   city: string = "";  
  13.   state: string = "";  
  14.   address: string = "";  
  15.   zip: string = "";  
  16.   email: string = "";  
  17.   password: string = "";  
  18.   isMarried: boolean;  
  19.   
  20.   
  21.   onSubmit(DemoForm) {  
  22.      //local variable  
  23.     console.log("Name :- " + this.name);  
  24.     console.log("City :- " + this.city);  
  25.     console.log("State :- " + this.state);  
  26.     console.log("Zip :- " + this.zip);  
  27.     console.log("Email :- " + this.email);  
  28.     console.log("Password :- " + this.password);  
  29.     console.log("IsMarried :- " + this.isMarried);  
  30.   
  31.   
  32.   }  
  33. }  
On the design side change ngModel attribute as below. Assign the variable which you created. If you create an object like a person and in-person you have a name, email, etc. then assign it as a person.name, person.email, etc.
  1. <div class="row mt-1">    
  2.     
  3.   <form #DemoForm="ngForm" (ngSubmit)="onSubmit(DemoForm)">    
  4.     <div class="form-group  col-6 m-2 p-2">    
  5.       <label for="inputAddress2">Name</label>    
  6.       <input type="text" class="form-control"  name="name" id="name" placeholder="Name" [ngModel]="name">    
  7.     </div>    
  8.     <div class="form-group col-6 m-2 p-2">    
  9.       <label for="inputEmail4">Email</label>    
  10.       <input type="email" class="form-control" id="email" name="email" placeholder="Email" [ngModel]="email">    
  11.     </div>    
  12.     <div class="form-group col-6 m-2 p-2">    
  13.       <label for="inputPassword4">Password</label>    
  14.       <input type="password" class="form-control" id="password"  name="password" placeholder="Password" [ngModel]="password">    
  15.     </div>    
  16.     
  17.     <div class="form-group  col-6 m-2 p-2">    
  18.       <label for="inputAddress">Address</label>    
  19.       <input type="text" class="form-control" name="address" id="address" placeholder="1234 Main St" [ngModel]="address">    
  20.     </div>    
  21.     
  22.     
  23.     <div class="form-group col-6 m-2 p-2">    
  24.       <label for="inputCity">City</label>    
  25.       <input type="text" class="form-control" id="city" name="city" [ngModel]="city">    
  26.     </div>    
  27.     <div class="form-group col-4 m-2 p-2">    
  28.       <label for="state">State</label>    
  29.       <select id="state" name="state" class="form-control" [ngModel]="state">    
  30.         <option selected>Choose...</option>    
  31.         <option>Gujarat</option>    
  32.         <option>UP</option>    
  33.         <option>Delhi</option>    
  34.       </select>    
  35.     </div>    
  36.     
  37.       <div class="form-group col-3 m-2 p-2">    
  38.         <label for="inputZip">Zip</label>    
  39.         <input type="text" class="form-control" id="zip" name="zip" [ngModel]="zip">    
  40.       </div>    
  41.     <div class="form-group m-2 p-2">    
  42.       <div class="form-check">    
  43.         <input class="form-check-input" type="checkbox" id="isMarried" name="isMarried" [ngModel]="isMarried">    
  44.         <label class="form-check-label" for="isMarried">    
  45.           Married    
  46.         </label>    
  47.       </div>    
  48.     </div>    
  49.     <button type="submit" class="btn btn-primary m-2 p-2">Submit Form</button>    
  50.   </form>    
  51. </div>    
Output
 
Template Driven Form In Angular 11
 

Set Data in Form

 
Giving value to elements in Template-driven forms is very easy. You need to assign value to a variable or object which you use. As you can see below here I only assign data to variables and it’s reflected in form. ngModel has two-way binding so we can get data using variable and also bind data using that variable.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.scss']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'FormsInAngular';  
  10.   
  11.   name: string = "Virat Kohli";  
  12.   city: string = "Delhi";  
  13.   state: string = "Delhi";  
  14.   address: string = "123 Delhi";  
  15.   zip: string = "12345";  
  16.   email: string = "virat@gmail.com";  
  17.   password: string = "12345";  
  18.   isMarried: boolean = true;  
  19.   
  20.   
  21.   onSubmit(DemoForm) {  
  22.     //forms value  
  23.     console.log(DemoForm.value);  
  24.   
  25.     //local variable  
  26.     console.log("Name :- " + this.name);  
  27.     console.log("City :- " + this.city);  
  28.     console.log("State :- " + this.state);  
  29.     console.log("Zip :- " + this.zip);  
  30.     console.log("Email :- " + this.email);  
  31.     console.log("Password :- " + this.password);  
  32.     console.log("IsMarried :- " + this.isMarried);  
  33.   
  34.   
  35.   }  
  36. }  
Output
 
Template Driven Form In Angular 11
 

Validation in Form

 
If you see any type of form it has validation. In simple form, it also has at least required validation. In Template Driven form we can also use validation.
 
Here are changes which you need to do in your existing form.
 
Template Driven Form In Angular 11
 
Explanation 
  • Here first of all we add conditions in submitting an event that our form is valid than the call submits method.
  • In the element we add two attributes first is required and second, we define the template variable and assign it to ngModel. Here you need to note one thing that your template variable and local variable name must be different otherwise it gives an error.
  • Next, we add div and add directive ngIf. In that condition, we define that is form is submitted and that element has an error. Here form submitted condition is required because when we use this without condition then its shows an error on the form load and that is not right.
  • And in that div, we also define another condition that our element has required the error or not because the element has many types of error like invalid email, required, min, max, etc.
Here is full html source code of form, 
  1. <div class="row mt-1">    
  2.     
  3.   <form #DemoForm="ngForm" (ngSubmit)="DemoForm.form.valid&& onSubmit(DemoForm)">    
  4.     <div class="form-group  col-6 m-2 p-2">    
  5.       <label for="inputAddress2">Name</label>    
  6.       <input type="text" class="form-control"  name="name" id="name" placeholder="Name" required [(ngModel)]="name" #nameVar="ngModel">     
  7.           
  8.       <div class="text-danger" *ngIf="DemoForm.submitted && nameVar.errors" >    
  9.         <p *ngIf="nameVar.errors.required">  Name Is Required.</p>    
  10.       </div>    
  11.     </div>    
  12.     <div class="form-group col-6 m-2 p-2">    
  13.       <label for="inputEmail4">Email</label>    
  14.       <input type="email" class="form-control" id="email" name="email" placeholder="Email" [(ngModel)]="email" #emailVar="ngModel" required>    
  15.           
  16.       <div class="text-danger" *ngIf="DemoForm.submitted &&emailVar.errors" >    
  17.         <p *ngIf="emailVar.errors.required"></p>Email Is Required.    
  18.       </div>    
  19.     </div>    
  20.     <div class="form-group col-6 m-2 p-2">    
  21.       <label for="inputPassword4">Password</label>    
  22.       <input type="password" class="form-control" id="password"  name="password" placeholder="Password" [(ngModel)]="password" #passwordVar="ngModel">    
  23.     </div>    
  24.     
  25.     <div class="form-group  col-6 m-2 p-2">    
  26.       <label for="inputAddress">Address</label>    
  27.       <input type="text" class="form-control" name="address" id="address" placeholder="1234 Main St" [(ngModel)]="address" #addressVar="ngModel">    
  28.     </div>    
  29.     
  30.     
  31.     <div class="form-group col-6 m-2 p-2">    
  32.       <label for="inputCity">City</label>    
  33.       <input type="text" class="form-control" id="city" name="city" [(ngModel)]="city"  #cityVar="ngModel">    
  34.     </div>    
  35.     <div class="form-group col-4 m-2 p-2">    
  36.       <label for="state">State</label>    
  37.       <select id="state" name="state" class="form-control" [(ngModel)]="state"  #stateVar="ngModel">    
  38.         <option selected>Choose...</option>    
  39.         <option>Gujarat</option>    
  40.         <option>UP</option>    
  41.         <option>Delhi</option>    
  42.       </select>    
  43.     </div>    
  44.     
  45.       <div class="form-group col-3 m-2 p-2">    
  46.         <label for="inputZip">Zip</label>    
  47.         <input type="text" class="form-control" id="zip" name="zip" [(ngModel)]="zip"  #zipVar="ngModel">    
  48.       </div>    
  49.     <div class="form-group m-2 p-2">    
  50.       <div class="form-check">    
  51.         <input class="form-check-input" type="checkbox" id="isMarried" name="isMarried" [(ngModel)]="isMarried"  #isMarriedVar="ngModel">    
  52.         <label class="form-check-label" for="isMarried">    
  53.           Married    
  54.         </label>    
  55.       </div>    
  56.     </div>    
  57.     <button type="submit" class="btn btn-primary m-2 p-2">Submit Form</button>    
  58.   </form>    
  59. </div>    
Output
 
Template Driven Form In Angular 11
 

Conclusion

 
So here we created Template Driven form, set data in form, get data from a form and also use validation. If you find this article useful kindly like this article and share it with your friends. Thank You.