Angular2 : Reactive Forms- Part 1

In angular latest version developments we have two ways of creating forms:

  •  Template Driven
  • Model Driven ( Reactive)

Major difference is that in reactive forms we don’t use ngModel directive. In reactive forms there is no direct binding of object model to directives, rather we create our own model i.e. FormControl , FormGroup instances inside the component.


To use Reactive Forms in App we have to import the ReactiveFormsModule from @angular/forms  and import/include into @NgModule – Imports

import { ReactiveFormsModule } from '@angular/forms';
import { FromsModule } from '@angular/forms';

 bootstrap: [AppComponent],
 declarations: [ AppComponent,...],
 imports: [
       FormsModule, ReactiveFormsModule, .... 
providers: [DataService,...]

** FormsModule for template-driven forms.

Creating a data entry form component using Reactive form approach:

FormControl:   a Class to track value and validation of individual form control.

Instantiate the Form controls at the component constructor level.

userId : FormControl;

this.userId = new FormControl();

FormGroup:  collection of FormControl instances.

ngOnInit()  – Initilaize the FormGroup instance.

demoDataEntryForm : FormGroup ;

ngOnInit() {
  this.demoDataEntryForm = new FormGroup({
           userId: this.userId


Next we have to bind the formgroup model to html controls.


<form [formGroup]="demoDataEntryForm" autocomplete="off" novalidate>


<textarea  formControlName="userId">



Can inject validations on Form control level while instantiating. = new FormControl('', [Validators.required, Validators.maxLength(250)]);

Here we can also hook up our own custom validation methods, like email/date validations..

Set/Patch FormGroup Control value:

We can dynamically set the control value using setControl  and  patchvalue

this.demoDataEntryForm.setControl(‘userId ‘, ‘100’);

this.demoDataEntryForm.patchValue( { userId : ‘101’ });  // Json format


Will cover up  FormBuilder and FormArray in next post..



Leave a Reply

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

You are commenting using your 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