Angular Js

Explain Angular Template-driven forms

Explain Angular Template-driven forms

Understand, Template-driven forms

This Article helps you to Understand, Template-driven forms

Objectives
Learn how template-driven forms and model-driven forms vary and resemble one another.
How to connect template input controls to component properties using the ngModel directive.
How to use the template-driven technique to implement form validation.
In the template-driven technique, how to submit and reset a form.


Overview
The simplest method for building forms in an Angular application is to use template driven forms. There is no requirement that we establish FormGroup and FormControl inside the Component.
Template-driven forms are just model-driven forms but driven by directives. Binding the HTML form to the component's model object is made possible via built-in directives in Angular. FormGroup and FormControl

First, using a few form elements, we construct a straightforward HTML form. The top-level FormGroup control will be created and converted to a template-driven form via the ngForm directive. Then, for each of the HTML form elements, we build a FormControl instance using the ngModel directive.


Setup An Initial Form Template
First, using a few form elements, we construct a straightforward HTML form. The top-level FormGroup control will be created and converted to a template-driven form via the ngForm directive. Then, for each of the HTML form elements, we build a FormControl instance using the ngModel directive.

1. Import FormsModule
We must import the FormsModule in order to use template-driven forms. The root module or a shared module is where we typically import it. All form directives and structures required to work with forms are included in the FormsModule.


// Open app.module.ts
// The directives we need to build template-driven forms are in the FormsModule

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";

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


2. Setup An Initial Form Template inside our Template (A Normal form Not a Template Form)


<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form novalidate>
        <div id="user-data">
          <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" class="form-control" required />
          </div>        

          <div class="form-group">
            <label for="email">Mail</label>
            <input type="email" id="email" class="form-control" required/>
          </div>
        </div>
       
        <div class="form-group">
          <label for="secret">Secret Questions</label>
          <select  id="secret"  class="form-control" >
<option *ngFor="let q of questions" [value]="q">{{q}}</option>
          </select>
        </div>
        <div class="form-group">
          <textarea rows="3" class="form-control"></textarea>
        </div>
   
        <button class="btn btn-primary" type="submit"> Submit </button>
 <button class="btn btn-default">Reset</button>
      </form>
    </div>
  </div>
</div>



3. Lets Convert our above simple form into a Template Driven Form

Directive : NgForm And NgModel
The Angular directives ngForm and ngModel are necessary for building Angular Template Driven Forms.
ngForm Creates a top-level FormGroup instance and binds it to a form to track aggregate form value and validation status.
NgForm directive has a selector which matches the HTML form tag.

local template reference variable


 <!-- Here, #userForm refers to the ngForm directive via a local template reference variable. -->
<!-- The ngForm directive creates a top-level FormGroup as one of its functions. -->

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

<!-- Now we can use #userForm variable to access the properties of Angular Form like value, valid,
invalid and errors. -->


If we execute this code right now, a blank object will be produced. This is due to the ngForm directive's inability to recognise every control present within the form> element it is connected to. With the ngForm directive, each template control needs to be manually registered. For this we need to do two things with each template form control:
Add the ngModel directive
Add the name attribute

To manage the template form control, the NgModel directive produces an instance of FormControl, and the name attribute instructs NgModel which key to keep for that FormControl in the parent FormGroup.


<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">

      <form (ngSubmit)="onSubmit()" #userForm="ngForm">
        <div id="user-data">

          <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username" class="form-control" required ngModel name="username" />
          </div>

          <div class="form-group">
            <label for="email">Mail</label>
            <input type="email" id="email" class="form-control" required ngModel name="email"/>
          </div>
        </div>

        <button class="btn btn-primary" type="submit"> Submit </button>
        <button class="btn btn-default">Reset</button>
      </form>
    </div>
  </div>
</div>



Two-way data binding in Template Form
Using two-way data binding is another method for interacting with template-driven forms.
We may use ngModel directive to build two-way data binding between a template form control and a variable on our component.

Therefore, whenever the user modifies the value in the template form control, the component's variable value immediately updates, and vice versa when we modify the component's variable.

Create a variable inside the component to which we will map the control before using the following syntax in the template control tag to map a template control using two-way data binding.


// This method of using the ngModel directive has a slightly different syntax
// In order to have a place to store the email, we first add a string property called email to our component

import { Component, ViewChild } from "@angular/core";
import { NgForm } from "@angular/forms";

class AppComponent implements OnInit {
  email: string;
answer = "";
  ngOnInit() {
  }
}




// To store the email that the user enters on the component, we add an email property.
// Next, two-way data binding was configured.

<input ... [(ngModel)]="email" >
<textarea name="questionAnswer" rows="3" class="form-control" [(ngModel)]="answer"></textarea>       

// The syntax for input property binding [] and output event binding () are combined to form the [()].
// The following could also be expressed in more detail:

<input ... [ngModel]="email" (ngModelChange)="email = $event" >


one way binding- to give that control a default value
two way binding- to instantly output control value 


Submit Form
To get access to form. add some local reference inside form tag #f here and pass same as an argument in onSubmit method
add directive ngForm inside it - it tells angular - please give access to JS object of this form you created automatically.

Fill the form and submit. now we can actual JS object created by angular.  


Here we can see that each control is of type FormControl and having multiple properties.
dirty property for example- it remain false until we change value of that control.
touched. - whether we focused on that field?



ACCESS Template Form Submission VIA VIEW CHILD
However, we may use a ViewChild decorator in our component code to obtain a reference to the ngForm object.
With the help of this decorator, we can refer to something from our template in our component.
Finally, we use the ViewChild decorator to decorate our property. The name of the local reference variable we want to connect to is passed to ViewChild as follows:

import { Component, ViewChild } from "@angular/core";
import { NgForm } from "@angular/forms";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  @ViewChild("userForm", { static: false }) signupForm: NgForm;

// Set Default value
  answer = "";
  user = {
    username: "",
    email: "",
    secretquestion: "" 
  };
  submitted = false;

  suggestUserName() {
    const suggestedName = "Superuser";   

    this.signupForm.form.patchValue({
      userData: {
        username: suggestedName,
      },
    });
  }

 
  onSubmit() {
    console.log(this.signupForm);
    this.submitted = true;
    this.user.username = this.signupForm.value.userData.username;
    this.user.email = this.signupForm.value.userData.email;
    this.user.secretquestion = this.signupForm.value.secret;   

    this.signupForm.reset();
  }
}




Summary
The Template-driven forms  is set up using ngForm directive
controls are set up using the ngModel directive
ngModel also provides the two-way data binding
The Validations are configured in the template via directives



Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram