Let’s play with Template Driven forms in Angular

Knoldus Blog Audio
Reading Time: 4 minutes

These days a wide range of sites are utilizing HTML Forms. WebForms are utilized to gather the information from the client and send it to the worker for handling.

Angular forms are divided into 2 types: 

(i) Template-driven forms.

(ii) Reactive forms.

In this blog, we will learn how to build the template form and how we can validate them using Angular form API. 

It includes the following basic status:

(i)   touched/ untouched: It describes the visiting state of the control.

(ii)  valid/ invalid: It describes the validity of the control.

(iii) dirty/ pristine: It describes the cleanness of the control.

Let’s take the example. Consider the below sample form: 

<form>
 <div>
   <label>Name</label>
   <input type="text" name="name"/>
 </div>
 <div>
   <label>Email</label>
   <input type="email" name="email"/>
 </div>
 <div>
   <label>Age</label>
   <input type="text" name="age"/>
</div>
 <button type="submit">Submit</button></form>

Following are the requirements for the above form:

Name: A unique name should be provided.

Email: A unique, valid email id is required.

Age: Age should be a number and it should be between 18 and 60.

Now, we will learn how to implement these specifications:

Template Driven Forms:

It supports the two-way data binding whenever the changes are made in the template In these forms, we write the logic, validation, controls in the HTML(template) part of the code.

When to use Template-Driven forms? 

We use the template-driven approach of the forms if the only app requires basic functionality for eg., SignUp/ SignIn. 

Advantages:

  1. Easy to add
  2. Less scalable
  3. Requires basic requirements

Now let’s understand how we implement template form in our angular project.

  1. First, we have to import the proper module in the AppModoule file i.e.;  FormModule.

This will activate the template-driven forms and it looks like that:

import {BrowserModule} from '@angular/platform-browser' // to provide essential service to run app
import {NgModule} from '@angular/core'
import {FormsModule} from '@angular/forms' // will active template driven
import {AppComponent} from 'src/app.component'; // importing root component
@NgModule({
 imports: [ BrowserModule, FormsModule ],
 declarations: [ AppComponent], // declaring AppComponent to run component.
 bootstrap: [ AppComponent ]
})
export class AppModule {}

2. Now, we must declare and import the root components i.e.; “AppComponent”. As a result, the AppComponent.ts file will look like this:

import {Component} from '@angular/core'
@Component({
selector: 'my-app',
 templateUrl: 'src/app.component.html'
})
export class AppComponent { }

3. In the starting of this blog, we define the structure of the form. This will be included in the AppComponent.html file. After that, we have to register the input element in our ngForm i.e.; we have to include ngModel for all elements.

=> ngForm provides us two basic functionality as follows:

(i) To retrieve all the registered control values

(ii) To retrieve the complete state of controls.

We can register it and attach the ngForm to the form like this :

<form #validateForm=”ngForm”>
 <input type="text" name="name" ngModel />
 <input type="text" name="email" ngModel />
 <input type="text" name="age" ngModel />
</form>

Now if we want to access the value, we can access it by using “valildateForm.value”. Till now, we have learned how to register the values and ngForm with HTML form control. 

Now we’ll learn how we can submit the form and how to apply validations on them.

1. For submission of the form:

It provides the “ngSubmit” and performs the same functionality as done by the onSubmit function. We can get the handler of submitting in component by passing form name to ngSubmit function and its implementation looks like this:

<form #validateForm="ngForm"(ngSubmit)="validate(validateForm)">
 …
</form>

We’ll provide the validation method in the “AppComponent” like this, resulting in access to the NgForm component when we submit the form.

validate (validateForm: NgForm) {
 console.log('Successfully Submitted');
 console.log(validateForm);
}
2. For validation of the form:

Validations on the form are done to ensure that data which is submitted by the user is correct and valid. Angular provides some validation are: required, maxLength, email, max, min, etc. If you want to know more about validation in the forms, you can visit here. So that, we can use the validation in our form as:

<form #validateForm="ngForm" (ngSubmit)="actionOnSubmit(validateForm)">
 <p>Is "validateForm" valid? {{validateForm.valid}}</p>
 ..
 <input type="text" name="name" ngModel required/>
 ..
 <input type="text" name="email" ngModel required/>
 ..
 <input type="text" name="age" ngModel required pattern="\\d{2,2}" />
</form>

As a result, {{validateForm.valid}} will print true if the form is valid.

As described above, age should be between 18-60. To get the user’s valid input, we need to do the validation which we’ll create by custom validation. Angular provides us the interface called “Validator”, through which we can write custom validation easily.

Let’s start to create a custom validator for Age:

First, we should know that when we are implementing the “Validator” we will overwrite the “validate” method. The validate method works with input and the expected output. Based on the user input, if the user entered invalid data, the method’s output can be null or undefined or some ValidationErrors object.

Custom Validator for Age: 

import { Directive } from '@angular/core';
import { NG_VALIDATORS, FormControl, Validator, ValidationErrors } from '@angular/forms'; // Will import the angular forms
@Directive({
selector: '[age-validate]',
providers: [{provide: NG_VALIDATORS, useExisting: AgeValidatorDirective, multi: true}]
})
export class AgeValidatorDirective implements Validator {
 validate(c: FormControl): ValidationErrors {
  const num = Number(c.value);
  const isValid = !isNaN(num) && num >= 18 && num <= 60;
  const message = {
    'age': {
      'message': 'The age must be a valid number between 18 and 60' // Will changes the error defined in errors helper.
    }
  };
  return isValid ? null : message;
}
}

Here, we’re checking the age between 18-60 in the method “validate” and return based on the input of the user. 

Now we can use this in our form for the age input and it will bind the custom validation to the field like this:

<input type="text" name="age" #age="ngModel" ngModel required age-validate/>

And if the user enters invalid information, we can disable the submit button and make it able only if the user enters valid information like this:

<button [disabled]="!myForm.valid">Submit</button>

The “validate” function in the “AppComponent.ts” returns the value which we can see the user entered data by through this:

validate (validateForm: NgForm) {
 console.log('Successfully Submitted');
 console.log(validateForm.value);
}

If we want to access the specific data we can access it by using the dot(.) operator like “validateForm.value.name”, this will return the name.

Conclusion:

In this blog, we’ve learned about template-driven forms, including building them and validating them by even creating our custom validation. Angular forms are very easy to validate as they require only minimal and easy changes in the form on the basis that user input is validated either they are valid or invalid. 

References:

https://angular.io/guide/form-validation

This image has an empty alt attribute; its file name is blog-footer.jpg

Written by 

Alka Vats is a Software Consultant at Knoldus. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.