Sub topic 10
Populating the array from existing data
This chapter assumes you know TypeScript, Angular standalone components, and basic reactive forms (FormControl, FormGroup, Validators). It also assumes you have built a FormArray of FormGroup controls, as in the order form from the previous chapters.
Why patchValue is not enough
Editing an existing record is common. You load an order from an API and the form must show its lines. The number of lines is unknown until the data arrives.
A FormArray does not create controls for you. setValue and patchValue only write values into controls that already exist. If the form starts with one row and the data has three, patchValue fills the first row and ignores the other two. setValue is stricter and throws an error when the array length does not match the data.
The clear-and-push pattern
The reliable approach has two steps. First remove every existing control with clear(). Then push one new control for each record.
setItems(data: { name: string; quantity: number }[]) {
this.items.clear();
data.forEach((d) => this.items.push(this.createItem(d.name, d.quantity)));
}This uses the createItem factory from the order form. It accepts initial values, so each new group starts with the record's data. The same factory builds empty rows for the "Add item" button, so both paths produce identical group shapes and validators.
Calling it from the component
Call setItems when the data arrives. Here the data comes from an input, but a router resolver or an HTTP call works the same way.
import { Component, effect, inject, input } 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">
<div formArrayName="items">
@for (item of items.controls; track item; let i = $index) {
<div [formGroupName]="i">
<input formControlName="name" />
<input type="number" formControlName="quantity" />
</div>
}
</div>
</form>
`,
})
export class OrderEditComponent {
private fb = inject(NonNullableFormBuilder);
lines = input<OrderLine[]>([]);
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
constructor() {
effect(() => this.setItems(this.lines()));
}
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)]],
});
}
setItems(data: OrderLine[]) {
this.items.clear();
data.forEach((d) => this.items.push(this.createItem(d.name, d.quantity)));
}
}The effect runs again whenever the lines input changes, so the form rebuilds itself for a new record.
What happens to form state
Clearing and pushing changes the form's state. The array and its parent recalculate their validity after each change. New controls start as pristine and untouched, so any "dirty" flag from earlier edits on the old rows is gone from those rows.
If you want the whole form to read as unmodified after loading, call markAsPristine() on the form once the rows are in place. That way a "unsaved changes" guard does not trigger just because you loaded data.
Each push also emits valueChanges on the array. If you subscribe to valueChanges, a load of 50 rows can fire 51 events (one for clear, one per push). Pass { emitEvent: false } to clear and push when you do not want listeners to run during the load, then call updateValueAndValidity() once at the end.
Common errors
- Using
patchValueto load a list of unknown length. Use clear and push instead. - Reusing the same control instance in two arrays. Always create a fresh group per record.
- Forgetting an empty-data case. With an empty list, the array ends with zero rows. If your
minItemsvalidator requires one, the form is invalid straight away, so decide whether to push a blank row.
Exercise
A form starts with one row. You call this.items.patchValue([{ name: 'A', quantity: 1 }, { name: 'B', quantity: 2 }]). How many rows does the form have afterwards, and what should you do instead?
Show answer
It still has one row, filled with the first record. patchValue does not create controls, so the second record is dropped. Call this.items.clear() and then push one group per record, for example with data.forEach((d) => this.items.push(this.createItem(d.name, d.quantity))).