How to capture data in Angular form using `ngModel` and `FormsModule` ?


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 following

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

Capturing the data in Template

First step

For capturing the data we need to use the ngForm which is working behind scene. So let’s reference it in the form tag as follows

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

The interpolation statement will display the data.

Second step

We have to tell the ngForm which input field , need to bind. We can use ngModel to bind the input controls as follows

    <div class="form-group">
    <label>Title</label>
    <input type="text" required class="form-control" name="title" ngModel >
   </div> 
   <div class="form-group ">
    <label>Description</label>
    <textarea class="form-control" minlength="10" name="desc" ngModel></textarea>
  </div>

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 from a form.

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.