Sub topic 10
Populating the array from existing data
This chapter assumes you can build a FormArray of FormGroups with NonNullableFormBuilder, bind it with formArrayName and [formGroupName]="i", and add or remove rows at runtime. It covers the case where the form starts from saved data, such as an order loaded from an API. You will build the controls to match the data, avoid the patchValue and setValue traps, and keep change events and form state correct.
Why a FormArray cannot be filled like a FormGroup
With a FormGroup, the controls are fixed when you create it. The keys are known, so patchValue({ name: 'Ann' }) always finds a control to write to.
A FormArray has no fixed shape. The data decides how many rows exist, and a record with five lines needs five groups. patchValue and setValue only write into controls that already exist. They never create new ones.
So populating a FormArray takes two steps:
- Make the array the right length by creating one control per record.
- Put the values into those controls. Usually you do this in step 1 by creating each control with its value.
The standard pattern: clear, then push
The most common approach empties the array and pushes one new control per record:
setItems(data: { name: string; quantity: number }[]) {
this.items.clear();
data.forEach((d) => this.items.push(this.createItem(d.name, d.quantity)));
}This works because createItem(name, quantity) accepts initial values. The new group is already filled when it is pushed, so no patchValue call is needed.
clear() removes every control and leaves an empty array. It is the same as calling removeAt until the array is empty, but it does it in one operation. Use it instead of reassigning the property. If you write this.form.controls.items = this.fb.array([]), the template may keep bindings to the old array.
Building the array at creation time
If the data is available when the form is created, you can skip clear() and build the array from the data:
import { Component, inject } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
interface OrderLine {
name: string;
quantity: number;
}
@Component({
selector: 'app-order-edit',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" />
<input type="number" formControlName="quantity" />
<button type="button" (click)="items.removeAt(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="reload()">Reload</button>
<button type="submit">Save</button>
</form>
`,
})
export class OrderEditComponent {
private fb = inject(NonNullableFormBuilder);
private saved: OrderLine[] = [
{ name: 'Keyboard', quantity: 1 },
{ name: 'Mouse', quantity: 2 },
];
form = this.fb.group({
items: this.fb.array(this.saved.map((l) => this.createItem(l.name, l.quantity))),
});
get items() {
return this.form.controls.items;
}
createItem(name = '', quantity = 1) {
return this.fb.group({
name: [name, Validators.required],
quantity: [quantity, [Validators.required, Validators.min(1)]],
});
}
reload() {
this.items.clear();
this.saved.forEach((l) => this.items.push(this.createItem(l.name, l.quantity)));
this.form.markAsPristine();
}
submit() {
console.log(this.form.getRawValue());
}
}The class field saved is declared before form. Field initializers run in order, so form can use this.saved and this.createItem. createItem is a method, so it is available on the prototype before any field runs.
Most real forms load data asynchronously, so reload() is the more common shape. The form exists first, empty or with one blank row. When the response arrives, you call a method like setItems.
The diagram below summarizes how to choose between the approaches.
What patchValue and setValue do with arrays
When the control count already matches, patchValue on the array works. When it does not match, the two methods behave differently:
import { FormArray, FormControl } from '@angular/forms';
const list = new FormArray([new FormControl('a', { nonNullable: true })]);
list.patchValue(['x', 'y']);
console.log(list.value); // ['x'] : 'y' is silently ignored
try {
list.setValue(['x', 'y']);
} catch (e) {
console.log((e as Error).message); // Cannot find form control at index 1
}| Situation | `patchValue` | `setValue` |
|---|---|---|
| More values than controls | Extra values are ignored without an error | Throws |
| Fewer values than controls | Patches the first controls and leaves the rest unchanged | Throws |
| Same length | Writes every value | Writes every value |
The silent behavior of patchValue is the common bug here. You load a record with three lines into a form that has one row, and the form shows only the first line. Nothing in the console tells you the other two were dropped.
Also remember that if your array holds groups, each value you pass must have the group's shape. patchValue tolerates missing keys inside a group, but setValue does not.
Controlling change events while loading
Each clear() and each push() emits valueChanges and statusChanges on the array and its parents. For ten rows that is eleven emissions. If a subscriber recalculates a total or calls an API on every change, you do that work eleven times, and it sees half-built states.
Both methods accept { emitEvent: false }. Suppress the events while loading, then trigger one update at the end:
setItems(data: { name: string; quantity: number }[]) {
this.items.clear({ emitEvent: false });
data.forEach((d) =>
this.items.push(this.createItem(d.name, d.quantity), { emitEvent: false }),
);
this.items.updateValueAndValidity();
this.form.markAsPristine();
}updateValueAndValidity() recomputes the array's value and validity and emits once, and the change propagates to the parent form. Without this call, the form's validity could be stale because the suppressed operations skipped the recalculation.
Pristine, dirty and touched after loading
Pushing controls marks the array as dirty in some versions and flows, and a freshly loaded form should usually look untouched. Two points matter:
- Controls created inside
createItemstart pristine and untouched, so a form built at creation time needs nothing extra. - When you reload an existing, already edited form, the form can still be dirty from earlier edits. Call
this.form.markAsPristine()and, if you show errors only after touch,this.form.markAsUntouched().
If you use a "Save" button that is disabled while the form is pristine, forgetting this step leaves it enabled right after a load.
Empty data
An API may return an empty list. With the clear and push pattern the array ends up with zero rows, which is valid. Decide what the user should see:
- If the form needs at least one row, add a blank one when the data is empty:
if (data.length === 0) this.items.push(this.createItem());. - If a
minItemsvalidator is attached to the array, an empty array will be invalid straight after loading. Run the load first, then checkitems.errors.
Resetting to the loaded data
form.reset() does not restore the original rows. It resets every existing control to its initial value or null, but the array keeps its current length, so rows the user added stay and rows the user removed do not come back.
To discard edits, keep a copy of the loaded data and call setItems(saved) again. This is what reload() does in the component above.
Common mistakes
- Calling
setValueorpatchValueon the array before the right number of controls exists. - Pushing one shared control instance several times. Each row needs its own control, so call
createIteminside the loop. - Mutating the data you loaded.
getRawValue()returns new objects, so the form never writes into yoursavedarray. Treat the form as its own copy. - Forgetting that
clear()triggers events and so can start extra requests invalueChangessubscribers.
Exercise
A form has a FormArray with two rows. You call items.patchValue([{ name: 'A', quantity: 1 }, { name: 'B', quantity: 2 }, { name: 'C', quantity: 3 }]). How many rows does the form show, and what should you do to show all three records?
Show answer
The form still shows two rows. The first two are updated with A and B, and C is ignored without an error. To show all three, call items.clear() and then push one control per record, for example data.forEach((d) => items.push(createItem(d.name, d.quantity))).
Exercise
You load 50 rows with clear() and 50 push() calls, and a valueChanges subscriber on the form calls an API each time. How do you make it call the API once, and which call must you add so the form's validity is correct afterward?
Show answer
Pass { emitEvent: false } to clear() and to each push(). Then call items.updateValueAndValidity() once at the end, which recalculates the value and validity and emits a single change.