ng:template_driven_form

Template Driven Form

In order to use ngForm, we need to import the Form module ni app.module.ts and your component.

When the submit button is clicked, we have the form to call function logForm(form.value).

<form #form="ngForm" (ngSubmit)="logForm(form.value)">
  <label>Firstname:</label>
  <input type="text" name="firstName" ngModel>
  <br>
  <label>Lastname:</label>
  <input type="text" name="lastName" ngModel>
  <br>
  <button type="submit">Submit</button>
</form>
import { Component, OnInit } from '@angular/core';
import {Form} from "@angular/forms";

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  logForm(value: Form) {
    console.log(value);

  }
}

The following output will print in the console.

Object { firstName: "first name", lastName: "last name" }

Item can be grouped by ngModelGroup, such as:

<form #form="ngForm" (ngSubmit)="logForm(form.value)">
  <label>Firstname:</label>
  <input type="text" name="firstName" ngModel>
  <br>
  <label>Lastname:</label>
  <input type="text" name="lastName" ngModel>
  <br>
  <fieldset ngModelGroup="personalInfo">
    <label>phone:</label>
    <input type="text" name="phone" ngModel>
    <br>
    <label>Address:</label>
    <input type="text" name="address" ngModel>
  </fieldset>
  <button type="submit">Submit</button>
</form>
​

The result would look like the following on click.

firstName: "first "
​lastName: "last"
​personalInfo: {…}
​​   address: "my addess, HK"
   ​​phone: "123456789"
  • ng/template_driven_form.txt
  • Last modified: 2019/11/22 16:26
  • by chongtin