How to capture data in Angular ReactiveForm using FormGroup


Form submission is an essential part of any commercial application. So lets learn about capturing data in Reactive Form which is give emphasize to component side.

app.module import

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

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
.....
 imports: [
    BrowserModule,
    ReactiveFormsModule,   
  ],

The following is required to capture data using FormGroup and Formcontrol.

  • Create a FormGroup
  • Bind the formGroup
  • Assigning formControlName

Create FormGroup and Bind it with Form

By using a Form Group we are creating alternative to Model class. The Group can be linked to a <form> using the [formGroup]=”todoForm”.

 todoForm = new FormGroup({
    item: new FormControl('MDT'),
    description: new FormControl('')
  });

Binding the control

We can replace the name property of input with formControlName. So that the data in the FormGroup will be automatically updated. and the template will look like

{{todoForm | json}}
<form [formGroup]="todoForm"   novalidation (ngSubmit)="OnSubmit()"  >
      <div class="form-group">
      <label>Title</label>
 <input type="text" required class="form-control" formControlName="item">
      </div>
      <div class="form-group ">
      <label>Description</label>
      <textarea class="form-control" formControlName="description" ></textarea>
      </div>
       <button  type="submit" class="btn btn-primary">Submit</button>
      </form>

The interpolation statement will display the data.

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 Reactive form using formGroup and formControl.

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.