How to capture data in Angular form using Model


Form submission is an essential part of any commercial application. So lets learn about capturing data in Template Driven Form ( Regular Form) which is hard coded in template.

app.module import

We have to import FormsModule to app.module.ts as follows

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

Capturing the data in Template

Model

The very first thing we need to do is create Model class with following fields.

export class Todo {
    constructor(
        public item: string,
        public description: string
    ) { }
}

and in the component define property todoForm and initialize it as follows

todoForm = new Todo('New todo', 'some text');

Now we are ready to capture the data using ngModel binding ( property). Also create a reference variable (#item=”ngModel”)

 <form #todoForm="ngForm">
   {{todoForm | json}}
   <div class="form-group">
    <label>Title</label>
    <input type="text"  class="form-control" name="title" [ngModel]="todoForm.item" #item="ngModel" >
   </div> 
   <div class="form-group ">
    <label>Description</label>
    <textarea class="form-control" minlength="10" [ngModel]="todoForm.desc" #desc="ngModel" name="desc"></textarea>
  </div>
    <button type="submit" class="btn btn-primary">Submit</button>
 </form>

The interpolation statement will display the data.

We have problem in property binding ( [ngModel]), that the model not updated as the control value changes. So we need a two way binding ( [()]))

Two way binding

Two way binding can be applied by placing event binding in ngModel as follows

     [(ngModel)]="todoModel.item"

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data in a form using a Model class.

A set form projects available in the Source-Code Page

These angular post may help you

[display posts tag=angular-form]

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.