Tuesday, September 29, 2020

Angular Template-Driven Form Example

In this post we’ll see how to create a template-driven form in Angular.

Importing FormsModule

You need to import FormsModule into the AppModule (app.module.ts) for Angular template-driven form to work. When you import the FormsModule in your component, Angular automatically creates and attaches an NgForm directive to the <form> tag in the template. Using NgForm you can track aggregated form value and validation status.

Add FormsModule in the imports section of the AppModule.
 imports: [

Data Model

Member class defines the data model reflected in the form.


export class Member {
  name: string;
  mail: string;
  membershipDate: Date;
  membershipType: string;
  constructor(name: string, mail: string, membershipDate: Date, membershipType: string) {
    this.name = name;
    this.mail = mail;
    this.membershipDate  = membershipDate;
    this.membershipType = membershipType;

Form Template

In this Angular template driven form example we’ll have a form with two input fields for name and email, a date picker for picking date and a drop down to select one of the option.


<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8">
      <h1>Membership Form</h1>
      <form (ngSubmit)="onSubmit()" #membershipForm="ngForm">
        <div class="form-group">
          <label for="name">Name</label>
          <input type="text" class="form-control" 
            ngModel name="name">                        
        <div class="form-group">
          <label for="email">email</label>
          <input type="email" class="form-control" 
            ngModel name="email">                        
        <div class="form-group">
          <label for="mdate">Membership Date</label>
          <input type="date" class="form-control" id="mdate"
            [ngModel]="currentDate | date:'yyyy-MM-dd'"  name="mdate">                        
        <div class="form-group">
          <label for="type">Membership Type</label>
          <select class="form-control" id="type"                    
              ngModel name="type">
            <option *ngFor="let mtype of membershiptypes" [value]="mtype">{{mtype}}</option>
        <button type="submit" class="btn btn-success">Submit</button>
  <div *ngIf="submitted">
    <div class="row">
      <div class="col-xs-12 col-sm-10 col-md-8">
        <p>Name: {{member.name}}</p>
        <p>email: {{member.mail}}</p>
        <p>Membership Date: {{member.membershipDate | date:'dd/MM/yyyy'}}</p>
        <p>Membership Type: {{member.membershipType}}</p>

Important points to note here are-

1. class="form-group" and class="form-control" are BootStrap framework classes used for styling. In Angular form a FormControl represents an individual form control where as FormGroup represents a collection of form controls as a group.

2. You would have noticed that ngModel is added with every element. This tells Angular that this element is a form control. Only for Membership date ngModel is used with square brackets meaning as a one way binding to get the current date. For other elements it is added only as ngModel to notify that it is a form control.

3. name="xxxx" specifies the name of form control. Using the specified name this form control is registered in the form.

4. For dropdown options are added using ngFor which iterates over an array called membershiptyes defined in the Component class.

5. Submit button is of type submit so it will trigger a submit event for that event binding is done at the form level.

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

6. membershipForm is a local reference that holds a reference to this form.

7. If the form is submitted it shows the entered values.

Component class (app.component.ts)

import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Member } from './member.model';

  selector: 'app-root',
  templateUrl: './app.component.html'
export class AppComponent {
  @ViewChild('membershipForm') memberForm : NgForm;
  membershiptypes = ['Silver', 'Gold', 'Platinum'];
  currentDate = new Date();
  member = new Member('', '', new Date(), '');
  submitted = false;

    this.submitted = true;
    this.member.name = this.memberForm.value.name;
    this.member.mail = this.memberForm.value.email;
    this.member.membershipDate = this.memberForm.value.mdate;
    this.member.membershipType = this.memberForm.value.type; 

1. @ViewChild decorator is used here to access the local reference. Since local reference membershipForm holds a reference to the JS object for the form so this way you can get access to the form object in your type script code.

2. Here we have currentDate field storing the current date, this is the field bound to the membership date in the template.

3. You create a member object of the Member class where you will assign the field values when the form is submitted (onSubmit() is called).

4. submitted field is intialized as false initially and changed to true when onSubmit() method is called. In the template there is an if condition that shows the entered values when submitted is true.

<div *ngIf="submitted">
Angular Template-Driven Form Example
Template-Driven Form

That's all for this topic Angular Template-Driven Form Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page

Related Topics

  1. Forms in Angular
  2. Angular Template-Driven Form Validation Example
  3. Angular Reactive Form Validation Example
  4. FormGroup in Angular With Examples
  5. Angular Cross Component Communication Using Subject Observable

You may also like-

  1. Location Strategies in Angular Routing
  2. Navigate to a Route Programmatically in Angular
  3. Angular ngIf Directive With Examples
  4. How to Create a Custom Observable in Angular
  5. BlockingQueue in Java Concurrency
  6. static Keyword in Java With Examples
  7. Sequence File in Hadoop
  8. Spring MVC File Upload (Multipart Request) Example

No comments:

Post a Comment