Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Template Driven Form ====== In order to use ngForm, we need to import the Form module ni app.module.ts and your component. ===== component.html ===== When the submit button is clicked, we have the form to call function ''logForm(form.value)''. <code> <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> </code> ==== component.ts ==== <code> 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); } } </code> ==== Output ==== The following output will print in the console. <code> Object { firstName: "first name", lastName: "last name" } </code> ==== Additional Info ==== Item can be grouped by ngModelGroup, such as: <code> <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> </code> The result would look like the following on click. <code> firstName: "first " lastName: "last" personalInfo: {…} address: "my addess, HK" phone: "123456789" </code> ng/template_driven_form.txt Last modified: 2019/11/22 16:26by chongtin