Home Angular Tutorials Angular Template-driven forms

Angular Template-driven forms

by aouidane.med.amine
49,044 views 25 min read

In this tutorial, we are going to learn how to use the template-driven forms approach to create forms.

Generally, angular provides two different approaches used to create forms. The template-driven forms and the reactive-forms.

In the template-driven form, we find all the validations and logic inside the HTML template whereas in the reactive-forms we find everything inside the component (form creation , validations … ).

So, a template-driven forms approach is very recommended if we want to create little forms and use the reactive-forms approach for the complex forms.

Table of Contents

How to use Template-driven forms

In this section, we are going to learn how to use template-driven forms through a simple example.

In this example, we are going to create a simple form that containing some fields, and we will try to do some basic operations and see how to set value dynamically, submit and reset the form and set form validations.

Import FormsModule

To use correctly the template-driven forms approach in our application, we need to import formsModule

formsModule provides two important directives.

  • NgForm to create the template-driven form and create the formGroup 
  • NgModel that allows us to create the formControl instances
				
					import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {FormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule
    AppRoutingModule,
    BrowserModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

				
			

Build The Template

The HTML form that we are going to create is a regular and classic HTML form.

So, we will find the <form> tag to create the form and the <input> tags to create the HTML inputs. Nothing special till now.

				
					<form>

  <div>
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName">
  </div>

  <div>
    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName">
  </div>

  <div>
    <label for="email">Email</label>
    <input type="text" id="email" name="email">
  </div>

  <div>
    <label for="age">Age</label>
    <input type="text" id="age" name="age">
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>

</form>

				
			

What is NgForm ?

Now we have the form template that contains all the elements we need, but angular till now doesn’t recognize the form and the formControls in the HTML template.

That’s why we need to add the ngForm directive.

Using this directive, angular will convert automatically the form into a template-driven form.

So the ngForm directive will detect the tag and bind itself to it and creates a top-level formGroup instance.

The ngForm is a powerful tool, it creates the formGroup and all the formControls inside that formGroup which has the ngModel directive.

The formGroup also detect the nested formGroup and looks out for any NgModelGroup to create a new formGroup instance for each NgModelGroup directive.

Export ngForm

Using the local template variables, we can export swiftly the ngForm.

It’s optional, but it is very useful to get access to the form values and validity status.

				
					<form  #userForm="ngForm" > </form>
				
			

What is NgModel ?

Generally, the form means noting if it doesn’t contain formControls.

To create formControl we just need to use ngModel directive.

This directive binds the tag to a formControl instance.

Once we have the formControl , we would have full access to the element, by tracking the user interactions, getting the element values and getting the validations‘ status.

In our example, we have 4 inputs, we just need to add the ngModel directive for each element to bind them to formControl instance.

				
					  <div>
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName" ngModel>
  </div>

  <div>
    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName" ngModel>
  </div>

  <div>
    <label for="email">Email</label>
    <input type="text" id="email" name="email" ngModel>
  </div>

  <div>
    <label for="age">Age</label>
    <input type="text" id="age" name="age" ngModel>
  </div>
				
			

Submit Form

Now, once we have created the form and all the related formControls,

we need to submit the form data to the component.

To do that, we can use the ngSubmit event. 

This event is based on Event binding concept, we use this concept to bind the ngSubmit to OnSubmitForm method in the component class.

When we click on the submit button, angular will fire the ngSubmit event.

As you see in the example, we are passing the local variable of the form to the method.

 The local variable is holding the reference of the userForm,

so we can access the form object in the component and extract all the form data.

				
					<form  #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">

  <div>
    <label for="firstName">First Name</label>
    <input type="text" id="firstName" name="firstName" ngModel>
  </div>

  <div>
    <label for="lastName">Last Name</label>
    <input type="text" id="lastName" name="lastName" ngModel>
  </div>

  <div>
    <label for="email">Email</label>
    <input type="text" id="email" name="email" ngModel>
  </div>

  <div>
    <label for="age">Age</label>
    <input type="text" id="age" name="age" ngModel>
  </div>

  <p>
    <button type="submit">Submit</button>
  </p>

</form>

				
			

Get Form Values

Now, we have every thing we need in our HTML template.

We have the formGroup , the formControls and the event binding of the submit action.

Now, if we want to get the form values, we just need to create a new method called OnSubmitForm() that bound to the ngSubmit event.

				
					  /* app.component.ts */
  onSubmit(userForm: NgForm): void {
    console.log(userForm.value);
  }
				
			

Reset Form

To reset the form, we do almost the same thing as the submit action.

We just create a new method in the component that accepts the form as a parameter, and we call it from the HTML file.

				
					    <button type="button" (click)="resetForm(userForm)">Reset</button>
				
			
				
					  /* app.component.ts */
  resetForm(userForm: NgForm): void {
    userForm.resetForm();
  }
				
			

We will get something like this as a result :

template_driven_forms_result

References

Clone The Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/template_driven_forms.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this tutorial, we have seen how to create a regular HTML form and convert it later to template-driven form using some important directives such as ngForm ans ngModel. And we have learned how to use each directive and the purpose of using it through a simple example.

I hope you enjoy reading this Tutorial.

You may also like