Template-Driven Forms In Angular

Template-Driven Forms In Angular

Angular Template-driven Forms is one of two ways to create forms in the framework. In this article, We will learn how to create a simple Template-driven forms sample app. We begin by creating a simple HTML form with a few form elements. The ngForm directive will build the top-level FormGroup control and transform it to a Template-driven form. Then, for each of the HTML form elements, we use the ngModel directive to construct a FormControl instance. We will learn how to submit form data to the component class later on. We will also learn how to initialize or reset the form data, as well as how to access the data in the component class using data binding.

We strongly advise you to go through our Angular Forms article if you haven't already. We addressed the core concepts of the Angular Forms Module in that essay.

What is Template-driven form?

We provide behaviors/validations in Template Driven Forms by using directives and attributes in our template and letting it function behind the scenes. Because everything happens in Templates, the component class requires very minimal code. This differs from reactive forms, where the logic and controls are defined in the component class.

Forms that are driven by templates

  • The ngForm directive is used to create the form,.
  • The ngModel directive is used to create the controls.
  • ngModel also has a two-way data binding feature.
  • Validations are set by using directives in the template.

Forms that are based on templates are popular.

  • The component class has a small amount of code.
  • It's a lot easier to set up.

While they are doing so,

  • It's difficult to dynamically add controls.
  • Unit testing is a difficult task.

Create the Example Application

To create a new application, using following command.

ng new tdf  --routing=true --style=css

Import FormsModule

The FormsModule must be imported in order to operate with Template-driven forms. We normally import it into a root or common module. The FormsModule is where you'll find all of the form directives and constructs you'll need to work with forms.

Add the import FormsModule from '@angular/forms'; to the app.module.ts file.

Also, add the FormsModule metadata property array to the imports metadata property array.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';        //import FormsModule
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule                    //Add in Imports Array
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

HTML Form

The first step is to create a template. A standard HTML form is shown below. A <form> tag is used to encapsulate it. Two text inputs (FirstName and LastName), an email (email), a radio button (gender), a checkbox (isMarried), and a choose list have all been added (country). This is a list of form elements.
<form>
 
  <p>
    <label for="firstname">First Name</label>
    <input type="text" id="firstname" name="firstname">
  </p>
 
  <p>
    <label for="lastname">Last Name</label>
    <input type="text" id="lastname" name="lastname">
  </p>
 
  <p>
    <label for="email">Email </label>
    <input type="text" id="email" name="email">
  </p>
 
  <p>
    <label for="gender">Geneder</label>
    <input type="radio" value="male" id="gender" name="gender"> Male
    <input type="radio" value="female" id="gender" name="gender"> Female
  </p>
 
  <p>
    <label for="isMarried">Married</label>
    <input type="checkbox" id="isMarried" name="isMarried">
  </p>
 
  <p>
  <label for="country">country </label>
  <select name="country" id="country">
    <option selected="" value=""></option>
    <option [ngValue]="c.id" *ngFor="let c of countryList">
      {{c.name}}
    </option>
  </select>
  </p>
 
  <p>
    <button type="submit">Submit</button>
  </p>
 
</form>

Component Class

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Template driven forms';
 
  countryList:country[] = [
    new country("1", "India"),
    new country('2', 'USA'),
    new country('3', 'England')
  ];
}
 
export class country {
  id:string;
  name:string;
 
  constructor(id:string, name:string) {
    this.id=id;
    this.name=name;
  }
}

ngForm

When we have a form with a few form elements, angular changes it to a Template-driven form automatically. The ngForm directive is responsible for this.

Angular template-driven forms are made possible with the ngForm directive. However, we do not need to include it directly. It's automatically added by Angular.

When we include FormsModule in our HTML template, Angular will look for any <form> tags. The ngForm directive is used by Angular to accomplish this. The ngForm directive identifies the <form> tag and binds to it automatically. To activate and bind the ngForm directive, you do not need to do anything.

The ngForm does the following tasks:
  • Identifies itself with the <Form> directive.
  • Creates a FormGroup instance at the top level.
  • For each child control with the ngModel directive, creates a FormControl object.
  • For each NgModelGroup directive, creates a FormGroup instance.

Using ngForm as the key, we may export the ngForm instance into a local template variable (ex: #contactForm="ngForm"). Using the template variable contactForm, we can access the many properties and methods of ngForm.

As a result, as seen below, edit the form element.
<form #contactForm="ngForm">

FormControl

The FormControl is the most fundamental component of Angular Forms. In an Angular form, it represents a single input field. The input element is bound to a FormControl by the Angular Forms Module. The FormControl instance is used to keep track of a form element's value, user interaction, and validation status. A FormControl is an individual Form element.

In our HTML template, we have six form elements. FirstName, lastName, email, gender, isMarried, and country are the fields. They must be bound to a FormControl instance. The ngModel directive is used to accomplish this. As illustrated below, add the ngModel directive to each control.
<input type="text" name="firstname" ngModel>

For each of the Form fields to which it is associated, ngModel will use the name property to generate a FormControl instance.

Submit Form

Except for the final step, which is submitting data to the component, you should now have the template ready.

To send the form data to the component class, we use the ngSubmit event. To link ngSubmit to the component class's OnSubmit method, we use event binding (parentheses). The ngSubmit event is triggered when the user presses the submit button.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">

In the onSubmit method, we pass the local template variable contactForm. The ngForm directive is referenced by contactForm. This may be used to extract data from form fields in our component class.

Final Template
The final template is as follows:
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
 
  <p>
    <label for="firstname">First Name</label>
    <input type="text" name="firstname" ngModel>
  </p>
 
  <p>
    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" ngModel>
  </p>
 
  <p>
    <label for="email">Email </label>
    <input type="text" id="email" name="email" ngModel>
  </p>
 
  <p>
    <label for="gender">Geneder</label>
    <input type="radio" value="male" name="gender" ngModel> Male
    <input type="radio" value="female" name="gender" ngModel> Female
  </p>
 
  <p>
    <label for="isMarried">Married</label>
    <input type="checkbox" name="isMarried" ngModel>
  </p>
 
  <select name="country" ngModel>
    <option [ngValue]="c.id" *ngFor="let c of countryList">
      {{c.name}}
    </option>
  </select>
 
  <p>
    <button type="submit">Submit</button>
  </p>
  
</form>

Receive Form Data

From our form, we need to accept data in component class. To accomplish this, we will need to add an onSubmit method to our component class. The reference to the ngForm directive, which we named contactForm, is passed to the submit method. The value method of the contactForm returns the form fields as a Json object.
onSubmit(contactForm) {
  console.log(contactForm.value);
}

The console.log command can be used to print the value to the console (contactForm.value)

Now, run the code and fill out the form with information. When you submit the data, open the Developer Console in your browser and inspect the output.
country: "1"
firstname: "Sachin"
email:"sachin@gmail.com"
gender: "male"
isMarried: true
lastname: "Tendulkar"

Template-Driven Forms In Angular

Local Variable

The ngFormFormControl, or FormGroup object can be assigned to a template local variable. This allows us to check the form's status, such as whether it's valid, submitted, and the value of the form elements, among other things.

ngForm

The local template variable #contactForm gives us access to the ngForm instance.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">

We can now use some of the attributes and methods to determine the status of the form. As an example,
<p>
  <button type="submit">Submit</button>
</p>
 
<pre>Value : {{contactForm.value | json }} </pre>
<pre>Valid : {{contactForm.valid}} </pre>
<pre>Touched : {{contactForm.touched  }} </pre>
<pre>Submitted : {{contactForm.submitted  }} </pre>

value: The value property returns an object containing each FormControl value.
valid: If the form is valid, it returns true; otherwise, it returns false.
touched: True if the user has filled up at least one field with a value.
submitted: If the form is submitted, this method returns true. Otherwise, false.

FormControl

Similarly, by setting the ngModel to a local variable, we can have access to the FormControl instance, as demonstrated below.
<input type="text" name="firstname" #fname="ngModel" ngModel>

The variable #fname now contains a reference to the FormControl's firstname. The properties of FormControl, such as value, valid, isvalid, and tocuhed, can then be accessed.
<p>
  <label for="firstname">First Name </label>
  <input type="text" name="firstname" #fname="ngModel" ngModel>
</p>
 
<pre>Value    : {{fname.value}} </pre>
<pre>valid    : {{fname.valid}} </pre>
<pre>invalid  : {{fname.invalid}} </pre>
<pre>touched  : {{fname.touched}} </pre>

value: The current value of the control is returned.
valid: If the value is valid, it returns true; otherwise, it returns false.
invalid: If the value is invalid, true; else, false.
touched: If the value is entered in the element, it returns true.

Nested FormGroup

A FormGroup is a group of FormControls. It can also have other FormGroup in it.

When we use the <Form> directive, the ngForm directive produces the top-level FormGroup behind the scenes.
<form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">

Using the ngModelGroup directive, we can create new FormGroup. Let's add the street, city, and pincode form controls to the address FormGroup.

Simply wrap the fields within a div element with the ngModelGroup directive applied to it, as seen below.
<div ngModelGroup="address">
 
    <p>
      <label for="city">City</label>
      <input type="text" name="city" ngModel>
    </p>
 
    <p>
      <label for="street">Street</label>
      <input type="text" name="street" ngModel>
    </p>
    <p>
      <label for="pincode">Pin Code</label>
      <input type="text" name="pincode" ngModel>
    </p>
 
</div>

Now, run the application and fill out the form. As you can see, the end outcome is as follows.
Value : {
  "firstname": "Sachin",
  "lastname": "Tendulkar",
  "email":"sachin@gmail.com"
  "gender": "male",
  "isMarried": true,
  "country": "1",
  "address": {
    "city": "Mumbai",
    "street": "Fashin Street",
    "pincode": "400600"
  }
}

Setting the Initial Value

Typically, the form is pre-filled with some default information. In the case of editing, we must display the current data to the user. The next tutorial, How to set value in a template-driven form, can be found here.

Validating the Form

Another key task is to validate the form. Validation in a template-driven form is addressed in the Validation lesson.

Conclusion

Template-driven Angular In comparison to reactive forms, forms are simpler. The FormsModule is the first module to be imported. The HTML form is then created. Angular recognizes the <form> tag and changes it to an Angular Form. Each form element is given the ngModel directive, which converts it to a FormControl. Finally, event binding is used to subscribe to the submit event.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post