FormBuilder
Editor’s note: This post was updated on 23 December 2020.
Reactive forms in Angular enable you to build clean forms without using too many directives. This is critical because:
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
.
We’ll cover the following in detail:
FormBuilder
?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.
For a quick visual overview of Angular form validation, check out the video tutorial below:
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.
For a deeper dive, check out our comprehensive tutorial on form groups and form controls 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:
FormControl
, you can pass sync functions in as the second argument.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.
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 FormControl
, FormGroup
, or FormArray
and reduces the amount of boilerplate required to build complex forms.
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.
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.
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:
import { Component, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Validators } 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: ['', Validators.required], 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); } }
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?
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.
Debugging Angular applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Angular state and actions for all of your users in production, try LogRocket.
LogRocket is like a DVR for web apps, recording literally everything that happens on your site, including network requests, JavaScript errors, and much more. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred.
The LogRocket NgRx plugin logs Angular state and actions to the LogRocket console, giving you context around what led to an error and what state the application was in when an issue occurred.
Modernize how you debug your Angular apps — start monitoring for free.
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. Happy hacking!
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowReact Native’s New Architecture offers significant performance advantages. In this article, you’ll explore synchronous and asynchronous rendering in React Native through practical use cases.
Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.
Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.
In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
7 Replies to "Angular reactive form validation with <code>FormBuilder</code>"
He Man this give this error error TS2339: Property ‘group’ does not exist on type ‘FormGroup’. on Typescript File
Import FormGroup and FormBuilder classes in your imports at the top of the file
doesn’t show anything about showing validation errors per each control
how do we send form data to back end
You say “…Copy the code block below into the employee.component.ts file:” but there is no code block below
Sorry about that, we’ve added it back in. Thanks for the catch
Beautifully written 👏👏👏