FormControl, FormGroup and FormBuilder in Angular Reactive Form

In one of the earlier blogs, I wrote about Template Driven Forms and Reactive Forms. In this blog, we will see about FormControl, FormGroup and FormBuilder in Angular in detail.

What is the Reactive form in Angular?

In Reactive Form, most of the code resides in the class file and not in the HTML template file. This is a good practice to use Reactive forms in complex scenarios. Reactive forms help us to achieve custom and dynamic validation.

Read:- Angular Interview Questions 

To use the Reactive form within your Angular project, import ReactiveFormsModule in app.module.ts file.

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],

FormControl, FormGroup in Angular

ReactiveFormsModule provides a set of classes and directives which help us to achieve many features to build Reactive forms, FormGroup and FormControl are some of them.

  • FormControl: All input fields defined in the HTML template are the instance of FormControl.
  • FormGroup: It is an instance of a set of form controls referred to as FormGroup

Below is the template code to create a basic input form. Note that, I have used formControlName for each field below.

<h1>Add New Products</h1>
    <form [formGroup]="addProductForm">
        <div class="form-group">
            <label>Product Name</label>
            <input type="text" class="form-control" formControlName="productName">
        </div>
        <div class="form-group">
            <select class="custom-select" formControlName="productCategory">
                <option selected>Select Category</option>
                <option *ngFor="let item of prodCategory">{{item}}</option>
            </select>
        </div>
        <div class="form-group">
            <label>Product Details</label>
            <input type="text" class="form-control" formControlName="productDetails">
        </div>
        <div class="form-group">
            <label>Product Cost</label>
            <input type="text" class="form-control" formControlName="productCost">
        </div>
    </form>

Import FormGroup and ReactiveFormsModule in the module file.

import {FormsModule, ReactiveFormsModule} from '@angular/forms';
 imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule]

Now, import FormGroup and FormControl in the component class file.

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-add-products',
  templateUrl: './add-products.component.html',
  styleUrls: ['./add-products.component.css']
})
export class AddProductsComponent implements OnInit {

  addProductForm = new FormGroup(
    {
      productName: new FormControl(''),
      productCategory: new FormControl(''),
      productDetails: new FormControl(''),
      productCost: new FormControl('')
    }
  );

  constructor() { }

  ngOnInit() {
  }

}

You may notice that each field is treated as the instance of a FormControl and the overall instance is FormGroup.

addProductForm = new FormGroup(
    {
      productName: new FormControl(''),
      productCategory: new FormControl(''),
      productDetails: new FormControl(''),
      productCost: new FormControl('')
    }
  );

SetValue and PatchValue

  • SetValue: It accepts an object that matches the structure of the FormGroup with control names as key.
  • PatchValue: It accepts an object and does its best to match the values. It can accept partial form group structure. Partial means, that not all control data is available to bind only a few control data are available.

SetValue

In setValue() we need all control data to match the structure and then bind the data to the form.

ngOnInit() {
    this.bindData();
  }

  bindData()
  {
    this.addProductForm.setValue(
      {
        productName:'Product1', 
        productCategory :'Electronics',
        productDetails : 'New model',
        productCost: 10000
      }
    );
  }

PatchValue

In patchValue() we may not require all control data to bind the data to the form.

ngOnInit() {
    this.bindData();
  }

  bindData()
  {
    this.addProductForm.patchValue(
      {
        productName:'Product1', 
        productCost: 10000
      }
    );
  }

FormBuilder Service in Angular

We have seen that all controls available in the HTML template file are instances of FormControl defined in the component class file. But, initializing 20 or 25 controls with FormControl instances is too boring as it is a repetitive task.

To avoid this repetitive task, Angular provides FormBuilder service to handle controls. group() method in FormBuilder takes an object with control names as key.

To use FormBuilder in the Angular project, first import FormBuilder from angular/forms as shown in the below code snippet below.

Next, use the group method which takes the control name as a key.

import { FormBuilder } from '@angular/forms';
addProductForm = this.formBuildr.group(
   {
     productName: [],
     productCategory: [],
     productDetails: [],
     productCost: []
   }
 );

Hope you like this blog on the Angular Reactive Forms approach which describes FormControl, FormGroup and FormBuilder in Angular.

Keep Following – SharePointCafe.Net

Leave a Comment

RSS
YouTube
YouTube
Instagram