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 services in Angular.

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 

So, 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, we are using formControlName with 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() {
  }

}

Here, we are treating each field 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

As we know, all the controls available in the HTML template file are the instances of FormControl which we define in the component class file. But, initializing more controls with FormControl instances is too boring as it is a repetitive task.

So, 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, firstly import FormBuilder from angular/forms as shown in the below code snippet below.

Secondly, 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: []
   }
 );

Conclusion

So, in this article, we learnt about Reactive forms in Angular. We also learnt about FormControl, FormGroup and FormBuilder in Angular. We are now comfortable with formbuilder and formgroup in angular.

Keep Following – SharePointCafe.Net

Leave a Comment

RSS
YouTube
YouTube
Instagram