Sub topic 10
Less Boilerplate with FormBuilder
This chapter assumes you have already built forms by calling new FormControl and new FormGroup yourself, and that you know how strictly typed forms infer value types and what nonNullable: true does. FormBuilder adds no new capabilities. It is a shorthand for creating the same FormControl, FormGroup, and FormArray objects. The shorthand is easy to read once you know its rules, and it has a few traps that cause type errors or runtime exceptions.
What FormBuilder Replaces
Here is a three-field form written with constructors:
import { FormControl, FormGroup, Validators } from '@angular/forms';
export const shippingForm = new FormGroup({
fullName: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
postcode: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.pattern(/^\d{5}$/)],
}),
express: new FormControl(false, { nonNullable: true }),
});This is the same form built with NonNullableFormBuilder:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-shipping-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="fullName" placeholder="Full name" />
<input formControlName="postcode" placeholder="Postcode" />
<label><input type="checkbox" formControlName="express" /> Express</label>
<button type="submit" [disabled]="form.invalid">Ship</button>
</form>
`,
})
export class ShippingFormComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
fullName: ['', Validators.required],
postcode: ['', [Validators.required, Validators.pattern(/^\d{5}$/)]],
express: false,
});
onSubmit(): void {
const value = this.form.getRawValue(); // { fullName: string; postcode: string; express: boolean }
console.log(value);
}
}Both versions produce identical objects at runtime. this.form.controls.postcode has the type FormControl<string> in both, and reset() sets each control back to its initial value, not null.
The Two Builders
FormBuilder is an injectable service provided in root. It comes in two variants:
| Builder | How to get it | Inferred control type for `''` | `reset()` result | Column |
|---|---|---|---|---|
| `FormBuilder` | `inject(FormBuilder)` | `FormControl<string \ | null>` | `null` |
| `NonNullableFormBuilder` | `inject(NonNullableFormBuilder)` or `inject(FormBuilder).nonNullable` | `FormControl<string>` | initial value |
inject(NonNullableFormBuilder) and inject(FormBuilder).nonNullable return equivalent builders. Use whichever form your team already uses. In new code, the non-nullable builder is almost always the better default, because a null you never asked for turns into ! assertions and ?? '' fallbacks across your components.
The plain FormBuilder makes nullable controls for backward compatibility. It matches what new FormControl('') did before typed forms arrived.
How the Builder Reads Each Config Entry
Each key in a group() config can hold one of several shapes. Most FormBuilder bugs come from not knowing which shape the builder thinks you wrote.
| Entry | Result |
|---|---|
| `false` | `FormControl<boolean>` with value `false` |
| `['', Validators.required]` | control with one sync validator |
| `['', [v1, v2], [asyncV]]` | control with sync and async validators |
| `[{ value: 'x', disabled: true }]` | disabled control with value `'x'` |
| `this.fb.control('', { updateOn: 'blur' })` | the control you passed in, unchanged |
| `this.fb.group({...})` | a nested group |
| `this.fb.array([...])` | a `FormArray` |
The array form takes up to three elements. If you need any other option, such as updateOn, switch to this.fb.control(value, options).
The Array-Value Trap
Since an array means "value plus validators", you cannot pass an array as a control's initial value directly:
// Wrong: 'urgent' is treated as the validators slot, and Angular throws at runtime
// tags: ['sale', 'urgent'],
// Right: wrap the value so it sits in position 0
// tags: [['sale', 'urgent']],
// Clearer: use control() explicitly
// tags: this.fb.control<string[]>(['sale', 'urgent']),If you want a list of separate controls instead of one control holding an array, use this.fb.array(...). Repeating fields are covered later in the tutorial.
Builder Methods
| Method | Builds | Notes |
|---|---|---|
| `group(config, options?)` | `FormGroup` | `options` takes `validators`, `asyncValidators`, `updateOn` |
| `control(value, opts?, asyncValidators?)` | `FormControl` | `opts` may be a validator, an array of validators, or an options object |
| `array(controls, validators?, asyncValidators?)` | `FormArray` | Each element follows the same config rules as group entries |
| `record(config, options?)` | `FormRecord` | Keys not known until runtime, all values the same type |
Validators that apply to the whole group go in the second argument of group():
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const atLeastOneContact: ValidatorFn = (g: AbstractControl): ValidationErrors | null =>
g.get('email')?.value || g.get('phone')?.value ? null : { contactRequired: true };
// inside a component:
// contact = this.fb.group({ email: '', phone: '' }, { validators: atLeastOneContact });Gotchas
Type Inference Widens on `null`
With the non-nullable builder, middleName: null infers FormControl<null>, and that type accepts nothing except null. Give the type explicitly with this.fb.control<string | null>(null).
Losing Types Through `any`
If the config object is built separately and typed as { [key: string]: any }, the resulting group becomes FormGroup<any> without any warning. Pass the config literal inline, or let TypeScript infer the config's type, so the control types survive.
Field Initializers Need `inject()`
form = this.fb.group(...) as a class field only works because fb is declared above it. Class fields initialize in source order. If you move form above private fb = inject(...), fb is still undefined when form runs, and you get a runtime error.
Builders Do Not Track Anything
A builder holds no state. Calling this.fb.group twice gives two independent groups. Reusing a builder across components is safe, and there is nothing to clean up.
Exercise
With private fb = inject(FormBuilder) (the nullable builder), what is the type of form.controls.age for form = this.fb.group({ age: [0, Validators.min(18)] }), and what does form.controls.age.reset() set the value to? How would you change the declaration so the answer is FormControl<number> and 0?
Show answer
The type is FormControl<number | null>, and reset() sets the value to null. Inject NonNullableFormBuilder instead, or use inject(FormBuilder).nonNullable, or declare that single control as this.fb.control(0, { nonNullable: true, validators: Validators.min(18) }).
Exercise
A teammate writes roles: ['admin', 'editor'] in a fb.group config, intending the control's initial value to be the array ['admin', 'editor']. What goes wrong, and what are two correct ways to write it?
Show answer
The builder reads the array as [value, validators]. It takes 'admin' as the value and tries to use the string 'editor' as a validator, which fails at runtime. Write roles: [['admin', 'editor']] so the array sits in position 0, or write roles: this.fb.control<string[]>(['admin', 'editor']).
Exercise
You need a postcode control that validates only on blur and is required. Why can't you use the array shorthand, and what should you write instead?
Show answer
The array shorthand only has slots for the value, the sync validators, and the async validators, so it has nowhere to put updateOn. Use postcode: this.fb.control('', { validators: Validators.required, updateOn: 'blur' }).