Sub topic 4
Creating a FormArray with FormBuilder
This chapter shows how to build a FormArray with FormBuilder instead of calling constructors by hand. It assumes you know TypeScript, Angular standalone components, and the basics of FormControl, FormGroup and Validators. It also assumes you have seen new FormArray([...]) from the previous chapter. Binding the array in a template and adding or removing rows come in later chapters. Here the focus is on creating the array correctly, with the right types.
Why use FormBuilder for arrays
You can build every form with constructors:
import { FormArray, FormControl, Validators } from '@angular/forms';
const emails = new FormArray([
new FormControl('[email protected]', { nonNullable: true, validators: [Validators.email] }),
new FormControl('[email protected]', { nonNullable: true, validators: [Validators.email] }),
]);This is explicit, but it gets noisy once the array sits inside a group that contains other groups and arrays. FormBuilder is an injectable service with factory methods named control, group, array and record. They accept short configuration values and create the controls for you. The result is the same object graph with less code.
FormBuilder.array() has this shape:
array(
controlsConfig: Array<unknown>,
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null,
): FormArrayThe first argument describes the initial entries. The second and third arguments attach validators to the array itself, not to its entries.
Choosing the right builder
Angular provides two injectable builders.
FormBuildercreates controls whose type includesnull, because a control can be reset tonull. A string control has the typeFormControl<string | null>.NonNullableFormBuildercreates controls that reset to their initial value, so the type staysFormControl<string>.
You can also use fb.nonNullable, a property on FormBuilder that behaves like NonNullableFormBuilder. This chapter injects NonNullableFormBuilder directly, which avoids null checks in the rest of your code.
import { inject } from '@angular/core';
import { FormBuilder, NonNullableFormBuilder } from '@angular/forms';
const nullable = inject(FormBuilder).array(['x']);
// FormArray<FormControl<string | null>>
const strict = inject(NonNullableFormBuilder).array(['x']);
// FormArray<FormControl<string>>Use NonNullableFormBuilder unless you deliberately want null to mean "no value". Typed forms are covered in a later chapter, but the builder choice affects every type you see from here on, so decide it up front.
What you can put in the config array
Each element of the first argument is a control configuration. The builder turns it into an AbstractControl using these rules.
| Element | Result |
|---|---|
| A plain value such as `'[email protected]'` | A `FormControl` with that initial value |
| An array such as `['[email protected]', Validators.email]` | A `FormControl` with the first item as the value and the rest as validators |
| An existing control, group or array | Used as is |
| A config object such as `{ value: '', disabled: true }` | A `FormControl` with that state |
The builder uses the same shorthand as fb.group(), so what you know about groups transfers. Here is a builder version of the first example:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-email-list',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<p>Entries: {{ emails.length }}</p>
@for (email of emails.controls; track email) {
<input [formControl]="email" />
}
`,
})
export class EmailListComponent {
private fb = inject(NonNullableFormBuilder);
emails = this.fb.array([
['[email protected]', Validators.email],
['[email protected]', Validators.email],
]);
}Each inner array is read as [initialValue, validators], so both entries become email-validated controls. The type of emails is FormArray<FormControl<string>>. The template binds each control directly with [formControl]. The next chapter covers binding with formArrayName in full.
The array-in-array trap
The shorthand has one sharp edge. An array element is always read as [value, validators]. If a control's own value is an array, such as a multi-select holding several ids, the builder misreads it.
// Wrong: the builder treats 1 as the value and [2, 3] as validators.
const wrong = this.fb.array([[1, 2, 3]]);
// Right: build the control explicitly so the array is its value.
const right = this.fb.array([this.fb.control([1, 2, 3])]);The first line fails at runtime or at compile time, because 2 and 3 are not validator functions. Whenever the entry's value is itself an array or an object, call this.fb.control(value) instead of using shorthand.
Creating an empty array
A form often starts with no entries, for example "add as many phone numbers as you like". An empty literal gives TypeScript nothing to infer the element type from, so state it with a type parameter:
phones = this.fb.array<string>([]);
// FormArray<FormControl<string>>Without <string>, later calls such as phones.push(...) have no useful element type to check against. Pass the type whenever the initial array is empty.
Building arrays from a factory method
Real forms usually repeat the same kind of entry many times. Defining the entry once in a method avoids copying the configuration into every place that adds a row. The next chapters use this pattern for groups, but it works for plain controls too:
createEmail(value = '') {
return this.fb.control(value, [Validators.required, Validators.email]);
}
emails = this.fb.array([this.createEmail('[email protected]'), this.createEmail()]);Because createEmail returns a ready-made control, the builder uses it as is. Later, emails.push(this.createEmail()) adds a new row with identical validation. If you later change the rules, you change them in one place.
Placing the array inside a group
A FormArray normally lives inside a FormGroup, which gives the form a named structure:
form = this.fb.group({
name: ['', Validators.required],
emails: this.fb.array([this.createEmail()]),
});
get emails() {
return this.form.controls.emails;
}The getter returns a typed FormArray<FormControl<string>>. Prefer form.controls.emails over form.get('emails'). The get method takes a string path and returns AbstractControl | null, so you lose the element type and have to cast. The typed controls property keeps it.
Validators on the array itself
The second argument of array() attaches validators to the array as a whole. These run against the array's value, a list of the entries' values, and the result is reported on the array, not on any single entry.
tags = this.fb.array(
[this.fb.control('angular'), this.fb.control('forms')],
{ validators: [Validators.maxLength(3)] },
);Validators.maxLength(3) reads control.value.length. For a FormArray that is the number of entries, so this array becomes invalid when it holds four or more tags. Passing an options object with a validators key is the current preferred style. Passing a bare ValidatorFn also works but offers no room for options like updateOn.
An array-level error does not make the entries invalid. The array's errors property holds it, and the parent group's valid goes false because a child is invalid. Per-entry rules and array-wide rules are covered together in the validation chapter.
Common mistakes
- Using plain
FormBuilderand expecting non-null types. Entries becomeFormControl<string | null>, and assigningemails.value[0]to astringvariable fails to compile. InjectNonNullableFormBuilder. - Forgetting the type for an empty array.
this.fb.array([])does not give you a usable element type. Writethis.fb.array<string>([]). - Shorthand with array values.
[[1, 2, 3]]is read as value plus validators. Usethis.fb.control([1, 2, 3]). - Putting entry validators in the second argument. The second argument validates the array. Validators for each entry belong to the entry's own config.
- Calling
inject()outside a field initializer or constructor.inject(NonNullableFormBuilder)must run in an injection context. Assign it in a class field, as the examples do.
Summary of the decisions
- Inject
NonNullableFormBuilderfor typed, non-null controls. - Use shorthand (
valueor[value, validators]) for simple entries. - Use
fb.control(...)when an entry's value is an array or an object. - Pass a type parameter such as
array<string>([])for empty arrays. - Keep entry creation in a factory method so every row is built the same way.
- Use the second argument only for rules about the array as a whole.
Exercise
Using NonNullableFormBuilder, write a field named scores that starts as an empty FormArray of numbers and becomes invalid when it holds more than five entries. Then say what type TypeScript gives it, and explain why this.fb.array([[10, 20]]) would not create a control whose value is the array [10, 20].
Show answer
scores = this.fb.array<number>([], { validators: [Validators.maxLength(5)] }); The type is FormArray<FormControl<number>>. The type parameter is needed because an empty literal gives no element type to infer, and the options object in the second argument attaches the array-level validator. In this.fb.array([[10, 20]]), the inner array is read as [initialValue, validators], so 10 becomes the control's value and 20 is treated as a validator, which is wrong. To store an array as a control's value, use this.fb.array([this.fb.control([10, 20])]).