Angular Forms (Template Driven Forms)

In this article, we are going to talk about Angular2 Forms. Forms are really important to collect the data from the users. Often, each website contains forms to collect the data. Let’s say our website has a registration form to collect the information from the users and we need to validate the form data as well before submitting the data.

Angular provides 2 different ways to collect and validate the data from a user.

  • Template-driven forms
  • Model-driven forms

In this article, we will learn how to use and validate the template driven forms. I am using bootstrap classes to apply some basic style to the form elements in order to give a visual indication to the user about the control's validity.

Let's open template-form.component.html and paste the following code to render a simple form.

HTML code

  1. <div class="container">  
  2.     <form class="form-horizontal" #userForm="ngForm" (ngSubmit)="submitForm(userForm.value)" novalidate>  
  3.         <div class="form-group">  
  4.             <label class="control-label col-sm-2" for="email">First Name:</label>  
  5.             <div class="col-sm-10">  
  6.                 <input type="text" #firstName="ngModel" minlength="5" maxlength="10" class="form-control" required placeholder="Enter first name"  
  7.                     name="firstName" ngModel>  
  8.                 <div *ngIf="firstName.errors && firstName.dirty">  
  9.                     <div class="alert alert-danger" *ngIf="firstName.errors.required">Name is required</div>  
  10.                     <div class="alert alert-danger" *ngIf="firstName.errors.minlength">Name should have minimum 5 characters</div>  
  11.                 </div>  
  12.             </div>  
  13.         </div>  
  14.         <div class="form-group">  
  15.             <label class="control-label col-sm-2" for="pwd">Email:</label>  
  16.             <div class="col-sm-10">  
  17.                 <input type="text" class="form-control" placeholder="Enter email" name="email" ngModel>  
  18.             </div>  
  19.         </div>  
  20.         <div ngModelGroup="address">  
  21.             <div class="form-group">  
  22.                 <label class="control-label col-sm-2" for="pwd">Country:</label>  
  23.                 <div class="col-sm-10">  
  24.                     <input type="text" class="form-control" placeholder="Enter country" name="country" ngModel>  
  25.                 </div>  
  26.             </div>  
  27.   
  28.             <div class="form-group">  
  29.                 <label class="control-label col-sm-2" for="pwd">City:</label>  
  30.                 <div class="col-sm-10">  
  31.                     <input type="text" class="form-control" placeholder="Enter city" name="city" ngModel>  
  32.                 </div>  
  33.             </div>  
  34.   
  35.             <div class="form-group">  
  36.                 <label class="control-label col-sm-2" for="pwd">Postal Code:</label>  
  37.                 <div class="col-sm-10">  
  38.                     <input type="text" class="form-control" #potalCode pattern="^[0-9][1-9]{4}$" placeholder="Enter postal code" name="postalCode"  
  39.                         ngModel>  
  40.                     <div *ngIf="potalCode.errors && potalCode.dirty">  
  41.                         <div class="alert alert-danger" *ngIf="potalCode.errors.pattern">Please enter proper postal code</div>  
  42.                     </div>  
  43.                 </div>  
  44.             </div>  
  45.         </div>  
  46.         <div class="form-group">  
  47.             <div class="col-sm-offset-2 col-sm-10">  
  48.                 <button type="submit" class="btn btn-primary" [disabled]="!userForm.valid">Submit</button>  
  49.             </div>  
  50.         </div>  
  51.     </form>  
  52. </div>  

HTML output screenshot

Angular

In the HTML code, as you can see I have used form tag at the top to declare the form, see the below code.

<form class="form-horizontal" #userForm="ngForm" (ngSubmit)="submitForm(userForm.value)" novalidate>

I have created the reference variable userForm using ngForm inbuilt directive to refer the form.

Whenever a user clicks on the Submit button of the form, ngSubmit event gets fired and here, I am passing the form values to submitForm() function using the reference variable. And submitForm() function is present in .ts file.

You can see that I am using ngModel inbuilt directive to register the input controls and its value with the form.

  1. <input type="text" #firstName="ngModel" minlength="5" maxlength="10" class="form-control" required placeholder="Enter first name" name="firstName" ngModel>  

For adding Validation:

In the above form, I have also added some basic validations, such as required and minlength. So, I am adding validation messages/css classes to the form control based on control's validity. Angular adds some classes to controls by default based on the control's state.

StateTrueFalse
Validng-validng-invalid
Controls value changedng-dirtyng-pristine
Control is visitedng-touchedng-untoched

So, we can easily use these classes to apply some basic validation/css styling to form element in template driven forms.

  1. <div class="form-group">  
  2.     <label class="control-label col-sm-2" for="email">First Name:</label>  
  3.     <div class="col-sm-10">  
  4.         <input type="text" #firstName="ngModel" minlength="5" maxlength="10" class="form-control" required placeholder="Enter first name"  
  5.             name="firstName" ngModel>  
  6.         <div *ngIf="firstName.errors && firstName.dirty">  
  7.             <div class="alert alert-danger" *ngIf="firstName.errors.required">Name is required</div>  
  8.             <div class="alert alert-danger" *ngIf="firstName.errors.minlength">Name should have minimum 5 characters</div>  
  9.         </div>  
  10.     </div>  
  11. </div>  

I have added firstName as a reference variable to the control and I’m using errors property to check the errors of the controls and based on the condition, I’m showing different error messages.

.ts file code

  1. import { Component } from '@angular/core'  
  2.   
  3. @Component({  
  4.     selector: 'my-app',  
  5.     templateUrl: './templatedrivenforms/template-form.component.html',  
  6.     styles: [  
  7.         `input.ng-valid{ border-left:10px solid green }  
  8.         input.ng-invalid { border-left:10px solid red }`  
  9.     ]  
  10. })  
  11. export class TemplateFormComponent {  
  12.     submitForm(values: any) {  
  13.         console.log(values);  
  14.     }  
  15. }  

Now, refresh the browser and fill all the required details.
Angular

Click "Submit" and check the console log, as shown below.

Angular

Once we click the Submit button, it calls that submitForm function and a console log as above.

In our next article, we will learn about Model-driven forms.

I hope this will help you. Thanks.

You can download the complete code from my GitHub repository.


Similar Articles