Member-only story

Understanding UntypedFormBuilder and FormBuilder in Angular

Chandan Kumar
5 min read6 days ago

--

Angular’s reactive forms module is a powerful tool for building dynamic, scalable, and testable forms in web applications. At the heart of this module lies the FormBuilder service, which simplifies the creation of FormControl, FormGroup, and FormArray instances. With the release of Angular 14, a significant enhancement was introduced: strictly typed forms. This brought about changes to how forms are handled, including the introduction of UntypedFormBuilder alongside the traditional FormBuilder. In this blog, we’ll dive into the details of both UntypedFormBuilder and FormBuilder, explore their differences, and explain why you might use both under certain conditions.

What is FormBuilder?

FormBuilder is a service in Angular’s @angular/forms package that provides a convenient, declarative way to create reactive forms. Instead of manually instantiating FormControl, FormGroup, or FormArray objects, FormBuilder offers shorthand methods like control(), group(), and array() to reduce boilerplate code. Here’s a simple example:

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

@Component({
selector: 'app-example',
template: `
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<input formControlName="name">
<button type="submit">Submit</button>
</form>
`
})

export class ExampleComponent {
myForm: FormGroup;

constructor(private fb: FormBuilder) {
this.myForm = this.fb.group({
name: ['']
});
}

onSubmit() {
console.log(this.myForm.value);
}
}

In this example, FormBuilder creates a FormGroup with a single FormControl named name. Before Angular 14, the type of myForm.value would be any, leaving developers without strict type safety. With Angular 14 and beyond, FormBuilder leverages TypeScript’s type inference to provide type safety automatically, making it a more robust choice for modern applications.

Enter Strictly Typed Forms in Angular 14

Angular 14 introduced strictly typed reactive forms, a long-requested feature that enhances type safety. Now, when you use FormBuilder, the form’s structure and values are inferred by TypeScript based on the initial values and…

--

--

Chandan Kumar
Chandan Kumar

Written by Chandan Kumar

Software Engineer | CS-Engineering Graduate | Mean Stack Developer | @Jobluu

No responses yet

Write a response