How to create a Angular reactive from with formGroup


Angular FormGroup and Form Control replace the necessity of a Model class for creating reactive form.

For using FormGroup you need to

  • import the Form Group, formControl
  • Create your group with form Controls
  • bind it to the form

The formGroup

import { FormControl, FormGroup } from '@angular/forms';
.... 
todoForm = new FormGroup({
    item: new FormControl('MDT'),
    description: new FormControl('')
  });

The default value can be passed along with the Form Control. Additionally there are two method for storing default, setValue and patchValue. Both of them are used to fill controls with predefined data.

setValue require that all the fields must be specified

setValue({item:'some item',description:'some description'});

while the patchvalue can be used to partially fill the controls

patchValue({item:'some item'});

Template

In Template you can use the formGroup and formControlName as follows

  <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" minlength="10" formControlName="description" ></textarea>
      </div>
       <button  type="submit" class="btn btn-primary">Submit</button>
      </form>

That is all about validation. Following angular form post may help you

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.