Let's Develop An Angular Application - Angular Template Driven Forms

Introduction

 
By reading this article you will learn about the Angular template-driven form approach.
 
We will create a simple form with few basic html controls and bind the data by using two-way data binding.
 
We will also learn how to pass form data from component template to component class.
 

Create a simple Form

 
Let’s create a simple user registration form using the Angular template-driven approach.
 
First we should create an Angular project
 
We can use the below CLI command to create an Angular project.
 
ng new our-project-name
 
If you need a more detailed read about Angular application architecture and installation, and project creation, you can read my below articles:
Next, let’s create a new component for Angular form.
 
Please follow the below steps to create a component.
  1. Open the project
  2. Open VS Code terminal by using either ViewàTerminal menu or using the shortcut keys Ctrl + ` (backtick)
  3. Execute the CLI command ‘ng generate component user-registration-form’
  4. Alternately, we can also use the short syntax ‘ng g c user-registration-form’ as well.
Let's Develop An Angular Application - Angular Template Driven Forms
 
So, we have successfully created an Angular application and a component.
 
Let’s test our application by running it using ‘ng serve’ command.
 
Before that, remove the boiler plate content in the ‘app.component.html’ file and add the newly-created component directive there.
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Let’s execute our application
 
Open the terminal again and execute ‘ng serve - -open’ command
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Here, - -open attribute will automatically open the application in browser. Otherwise, we should open the page by using the url http://localhost:4200/
 
When we open the application in the browser, we will get the result as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Awesome!
 
We have successfully created the basic requirement for create an Angular form.
 

Install Bootstrap

 
Let’s install bootstrap to add simple bootstrap css classes.
 
Execute the cli command npm install –save bootstrap
 
This will take a few seconds to install the bootstrap library.
 
Then add the bootstrap css file path in Angular.json file
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
We can test the bootstrap installation by adding simple css class to a button control and check result in browser.
 
Please add a button in ‘user-registration-form.component.html’ template file as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
If our application is already running, please stop it by pressing the ‘Ctrl + C ‘ in terminal and re-run using the ng serve command to make the bootstrap styles applicable in your application.
 
If the bootstrap is installed and configured correctly, the button will be displayed in the browser as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 

Import FormsModule

 
In order to use Angular forms in our application, we should import the ‘FomsModule’ from @angular/forms library.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 

Create a simple Angular form

 
Let’s create a simple form.
 
Open the ‘user-registration-form.component.html’
 
Add a <form> element first.Then I have added an <h2> element for our form caption.
 
Then I added 2 text boxes as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
In the above html template file I have only added 2 input boxes and 2 labels for them.
 
But adding some div elements and few bootstrap style classes makes the file a bit bulky. But they are added for improve the appearance only.
 
Here for=” ” attribute is used with label control to focus the curser to the corresponding text box if we click the label. The value specified in for is the id value of the first name textbox.
 
Save the files and check the result in browser.
 
The result will be like the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
We can add a few more controls to get more information from the user.
 
Don’t worry about the bootstrap style classes. We can refer to the bootstrap documentation to understand various form controls.
 
Click the link to visit bootstrap documentation https://getbootstrap.com/docs/4.4/components/forms/
 
Since this is a user registration screen, we need to provide an option to select gender.
 
For this we can use radio button group.
 
To get the bootstrap syntax for adding radio button group, we can access the above link.
 
I have copied the html statements for radio buttons and changed the properties like name id as per my requirements.
 
Please refer to the html statement with bootstrap style classes.
  1. <div class="form-check form-check-inline">    
  2.     <input class="form-check-input" type="radio" name="gender" id="gender_Male" value="Male" checked>    
  3.     <label class="form-check-label" for="gender_Male"> Male </label>    
  4.  </div>    
  5.  <div class="form-check form-check-inline">    
  6.     <input class="form-check-input" type="radio" name="gender" id="gender_Female" value="Female" >    
  7.     <label class="form-check-label" for="gender_Female"> Female </label>      
  8. </div>   
Then I have added dropdown control by using the below html statements
 
I have copied the statements from bootstrap documentation site.
  1. <div class="form-group">    
  2.     <label for="paymentMode">Payment Mode</label>    
  3.     <select class="form-control" id="paymentMode">    
  4.         <option>Monthly</option>    
  5.         <option>Quarterly</option>    
  6.         <option>Yearly</option>    
  7.     </select>    
  8. </div>     
Then I have added a check box control for enabling notification.
 
Please refer to the html statements for adding a checkbox below.
  1. <div class="form-check">    
  2.        <input class="form-check-input" type="checkbox" value="" id="enable_notification" name="notification" >    
  3.        <label class="form-check-label" for="enable_notification"> Enable Notification  </label>    
  4. </div>    
Finally, I added a button control as below.
  1. <div class="form-group row">    
  2.     <div class="col-sm-10">    
  3.        <button type="button" class="btn btn-primary">Register</button>    
  4.    </div>    
  5. </div>     
Now our template file will look like the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Save the file and check the browser. We will get the result as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Great!
 
We have created a decent looking form!
 

How to access the form control values?

 
By importing the ‘FormsModule’ library, Angular takes the control over the form using ‘ngForm’ directive.  ngForm is internal to Angular and it will be available with all forms.
 
When Angular processes the template and identifies a form element, it will add ngForm directive. We never have to add this ourselves.
 
To learn more, visit https://angular.io/api/forms/NgForm
 
When ngForm directive is associated with a form, Angular will create an instance of the ngForm.
 
To access the ngForm instance, we can use template reference variable.
 
For example, add #userRegForm=”ngForm” inside the form tag.
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Now we can access the form instance using ‘userRegForm’ .
 
Let’s check the value of userRegForm.
 
Add the below 2 interpolation statements in our template file:
 
Type : {{userRegForm}}
{{userRegForm | json}}
 
Please refer to the screenshot below:
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Save the file and check results in browser.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
As we can see in the above screenshot, userRegForm is an object.
 
In the screenshot, we can see the properties of the userRegForm object as well.
 
We can use these different properties to control our form.
 
In these properties, one of the important ones is value { } property.
 
This property is used to store the form control values
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
But it will be empty because, Angular is not aware of our controls.
 

Use ngModel

 
To let the Angular be aware about the controls, we need to add the ngModel directive in each control.
 
Let’s try this in our name text box. Please refer to the screen shot below:
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Then display the value property by using the below statement.
 
{{userRegForm.value | json}}
 
In this way we can access each property separately.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Save the file and check the result in browser.
 
When we type the name in the name text box, the value property will also change.
 
Please refer to the screen shot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Let’s add ngModel for the rest of the controls.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Awesome!!
 
We have successfully created an Angular form using ngForm directive and accessed the form control values using ngModel directive.
 

Manage the form data using two-way binding

 
We can access the form control values from our component class typescript file using two-way data binding.
 
For this, let’s create an interface for our user model
  1. Crete a folder inside app folder ‘data’
  2. Create typescript file and name it as User.model.ts
  3. Open the User.model.ts file and create an interface with name ‘user’
  1. export interface User{  
  2.     name :string,  
  3.     email:string,  
  4.     gender:string,  
  5.     paymentMode:string,  
  6.     notification:boolean  
  7.   
  8. }  
Open the our component’s typescript file ‘user-registration-form.component.ts’
 
Create an object of type user as below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Next, we need to bind the registerUser object to the form.
 
We can use the two way binding for this.
 
Replace the ngModel directive as [(ngModel)] ="registerUser.name"[( )]is called ‘Banana in the Box’ syntax.
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Then, we displayed the user data model object using interpolation to verify the 2 way binding.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Save the screen and check the result in browser.
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
As you can see in the above screenshot, all controls are populated with the user data from the component class using two way binding.
 
We can check the 2 way binding by changing the value in the form.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
We can see the user model values are changing based on the changes in the form control.
 

Pass the form data from template to component class

 
We can use the form’s template reference variable ‘userRegForm’ to pass the form data to the component class.
 
I have created a method register () in component class with an argument of type ‘ngForm’ And , log the form data to the console
 
Please refer below:
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
We should import the NgForm class from @angular/forms
 
import { NgForm } from '@angular/forms'
 
Then add ngSubmit event to the form element and bind the register() to it.
 
Please refer to the screenshot below.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
Then, change the button type to ‘submit’ and save the project.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
To see the results, fill the form data and click the register button .
 
Then open the browser console and we will see the form data will be logged as in the below screenshot.
 
Let's Develop An Angular Application - Angular Template Driven Forms
 
We can add more logics to handle the form data in register() method in the template class.
 

Summary

 
In this article, we have learned about Angular forms.
 
There are two approachesin Angular to implement forms.
 
They are, template driven approach and reactive forms.
 
Here we learned about the template-driven approach. This approach is simple and suitable for creating basic forms like login forms.
 
Then we have implemented the two-way data binding for communicating the user data.
 
Happy Learning Let's Develop An Angular Application - Angular Template Driven Forms


Similar Articles