Sub topic 3
Populating Dynamic FormArrays from Existing Data
Assume you know TypeScript, Angular templates, standalone components, and basic reactive forms.
Populating the array from existing data
A FormArray does not create controls when you call setValue() or patchValue(). Create one control or group for each record first.
type ItemData = { name: string; quantity: number };
items = this.fb.array([this.createItem()]);
createItem(data: ItemData = { name: '', quantity: 1 }) {
return this.fb.group({
name: [data.name, Validators.required],
quantity: [data.quantity, [Validators.required, Validators.min(1)]],
});
}
setItems(data: ItemData[]) {
this.items.clear();
for (const item of data) {
this.items.push(this.createItem(item));
}
}Call setItems() after an HTTP request returns. clear() removes the old controls before the new controls are added.
Typed forms and FormArray
Typed forms let TypeScript check control access and values. NonNullableFormBuilder also prevents ordinary controls from producing null values.
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
items: this.fb.array([this.createItem()]),
});
get items() {
return this.form.controls.items;
}Now this.items.controls is known to contain item groups, and this.form.getRawValue().items is an array of { name: string; quantity: number }.
Rendering lists efficiently with `track`
Track each control by its identity. Angular can then preserve the DOM for unchanged rows when another row is inserted or removed.
<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>Reacting to changes with `valueChanges`
Every control emits through valueChanges. Subscribe to the array when another part of the component must react to row changes.
items.valueChanges.subscribe(value => {
console.log('Items changed:', value);
});In a long-lived component, clean up subscriptions with Angular's takeUntilDestroyed pattern.
Nested FormArrays
A group can contain another array. For example, an order can contain shipments, and each shipment can contain packages.
Create the inner array in the factory method. In the template, nest formArrayName and [formGroupName] at each level.
Testing dynamic forms
Test behavior rather than private implementation details.
it('adds and removes items', () => {
const component = fixture.componentInstance;
component.addItem();
expect(component.items.length).toBe(2);
component.removeItem(1);
expect(component.items.length).toBe(1);
});Also test that setItems() creates the expected number of controls and preserves each record's values.
Exercise
Why must setItems create controls instead of only calling patchValue?
Show answer
patchValue updates controls that already exist. It does not create missing FormArray entries.