Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because:

  • JavaScript frameworks typically caution against using clustered templates
  • Form logic now lies in the component class

Essentially, Angular reactive forms give developers more control because every decision related to inputs and controls must be intentional and explicit.

To ensure the quality of your data, it’s always a good practice to validate reactive form input for accuracy and completeness. In this tutorial, we’ll show you how to validate reactive forms in Angular using FormBuilder.

To follow along, make sure you have the latest versions of Node.js (15.5.0) and Angular (11.0.5) installed, along with the Angular CLI (11.0.5). You can download the starter project on GitHub.

Form controls and form groups in Angular

Form controls are classes that can hold both the data values and the validation information of any form element, which means every form input you have in a reactive form should be bound by a form control. These are the basic units that make up reactive forms.

FormControl is a class in Angular that tracks the value and validation status of an individual form control. One of the three essential building blocks in Angular forms — along with FormGroup and FormArray — FormControl extends the AbstractControl class, which enables it to access the value, validation status, user interactions, and events.

Form groups are constructs that basically wrap a collection of form controls. Just as the control gives you access to the state of an element, the group gives the same access, but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.

FormGroup is used with FormControl to track the value and validate the state of form control. In practice,  FormGroup aggregates the values of each child FormControl into a single object, using each control name as the key. It calculates its status by reducing the status values of its children so that if one control in a group is invalid, the entire group is rendered invalid.

What is form validation in Angular?

Form validation in Angular enables you to verify that the input is accurate and complete. You can validate user input from the UI and display helpful validation messages in both template-driven and reactive forms.

When validating reactive forms in Angular, validator functions are added directly to the form control model in the component class. Angular calls these functions whenever the value of the control changes.

Validator functions can be either synchronous or asynchronous:

  • Synchronous validators take a control instance and return either a set of errors or null. When you create a FormControl, you can pass sync functions in as the second argument.
  • Asynchronous validators take a control instance and return a Promise or an Observable that later issues either a set of errors or null. You can pass async functions in as the third argument when you instantiate a FormControl.

Depending on the unique needs and goals of your project, you may choose to either write custom validator functions or use any of Angular’s built-in validators.

Without further ado, let’s get started building reactive forms.

What is FormBuilder?

Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. FormBuilder in Angular helps you streamline the process of building complex forms while avoiding repetition.

Put simply, FormBuilder provides syntactic sugar that eases the burden of creating instances of FormControlFormGroup, or FormArray and reduces the amount of boilerplate required to build complex forms.

How to use FormBuilder

The example below shows how to build a reactive form in Angular using FormBuilder.

You should have downloaded and opened the starter project in VS Code. If you open the employee.component.ts, file it should look like this:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you end up repeating yourself. FormBuilder helps solve this efficiency problem.

Registering FormBuilder

To use FormBuilder, you must first register it. To register FormBuilder in a component, import it from Angular forms:

import { FormBuilder } from ‘@angular/forms’;

The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the employee.component.ts file and copy in the code block below.

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = this.fb.group({
    firstName: [''],
    lastName: [''],
    age: [''],
    stackDetails: this.fb.group({
      stack: [''],
      experience: ['']
    }),
    address: this.fb.group({
        country: [''],
        city: ['']
    })
  });
constructor(private fb: FormBuilder) { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.

How to validate forms in Angular

Using reactive forms in Angular, you can validate your forms inside the form builders.

Run your application in development with the command:

ng serve

You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.

import { Validators } from '@angular/forms';

You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the employee.component.ts file:

The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the employee.component.html file and make sure the submit statement looks like this:

<button type=”submit” [disabled]=”!bioSection.valid”>Submit Application</button>

If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool?

Displaying input values and status

Let’s say you want to use the value and status properties to display, in real-time, the input values of your reactive form and whether it can be submitted or not.

The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your employee.component.html file and copy in the code block below:

<form [formGroup]="bioSection" (ngSubmit)="callingFunction()">
    <h3>Bio Details
</h3>

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label> <br>
<label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label> <br>
<label>
    Age:
    <input type="text" formControlName="age">
  </label>
<div formGroupName="stackDetails">
    <h3>Stack Details</h3>

    <label>
      Stack:
      <input type="text" formControlName="stack">
    </label> <br>

    <label>
      Experience:
      <input type="text" formControlName="experience">
    </label>
  </div>
<div formGroupName="address">
    <h3>Address</h3>

    <label>
      Country:
      <input type="text" formControlName="country">
    </label> <br>

    <label>
      City:
      <input type="text" formControlName="city">
    </label>
  </div>
<button type="submit" [disabled]="!bioSection.valid">Submit Application</button>
  <p>
    Real-time data: {{ bioSection.value | json }}
  </p>
  <p>
    Your form status is : {{ bioSection.status }}
  </p>
</form>

This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be found here on GitHub.

Conclusion

This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms.

Leave a comment

Your email address will not be published.