Sub topic 13
Reacting to changes with valueChanges
This chapter assumes you can build a FormArray of FormGroups, bind it with formArrayName, and add or remove rows. You also need basic RxJS: subscribe, pipe, and operators.
What valueChanges emits
Every control, group and array has a valueChanges observable. It emits the control's new value each time the value changes. On a FormArray, the emitted value is an array with one entry per control.
The array emits when:
- a child control's value changes, for example when the user types
- you call
push,insert,removeAtorclear - you call
setValueorpatchValueon the array or a parent
valueChanges does not emit when you subscribe, so it never reports the initial value. Add startWith if you need that value. A sibling observable, statusChanges, emits VALID, INVALID, PENDING or DISABLED whenever validity changes.
Example: a live order total
This component recalculates a total whenever a line changes, is added, or is removed.
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { startWith } from 'rxjs';
@Component({
selector: 'app-order-total',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<div formArrayName="lines">
@for (line of lines.controls; track line; let i = $index) {
<div [formGroupName]="i">
<input type="number" formControlName="price" />
<input type="number" formControlName="quantity" />
<button type="button" (click)="lines.removeAt(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="addLine()">Add line</button>
<p>Total: {{ total() }}</p>
</form>
`,
})
export class OrderTotalComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
lines: this.fb.array([this.createLine()]),
});
total = signal(0);
constructor() {
this.lines.valueChanges
.pipe(startWith(this.lines.value), takeUntilDestroyed())
.subscribe((values) => {
this.total.set(
values.reduce((sum, l) => sum + (l.price ?? 0) * (l.quantity ?? 0), 0),
);
});
}
get lines() {
return this.form.controls.lines;
}
createLine() {
return this.fb.group({
price: [0, Validators.min(0)],
quantity: [1, Validators.min(1)],
});
}
addLine() {
this.lines.push(this.createLine());
}
}The typed value is Partial<...>[] because disabled controls are left out of value. That is why the code uses ?? 0.
Subscribe once, at the array
You could subscribe to each row's valueChanges as rows are created. That is harder to maintain. Rows come and go, and each subscription must be cleaned up when its row is removed. If you forget, the stale subscription keeps running.
Subscribe to the array once instead. It emits for every row change and for every structural change, and the single subscription ends when the component is destroyed. Per-row subscriptions are justified only when one row's logic is truly independent, such as a price lookup that fills in a field in that row.
Avoiding extra emissions
Each push emits once. Loading ten records with ten pushes emits ten times. If your handler is costly, pass { emitEvent: false } to the calls that support it, such as setValue and patchValue. Then trigger one update at the end. clear and removeAt also accept this option.
this.lines.clear({ emitEvent: false });
data.forEach((d) => this.lines.push(this.createLine(), { emitEvent: false }));
this.lines.updateValueAndValidity();A handler that writes back into the same form, for example with patchValue, can loop forever. Pass { emitEvent: false } on that write, or compare values before writing.
Exercise
A handler subscribed to lines.valueChanges does not run when the page first loads, so the total shows 0 even though one default line exists. How do you fix it?
Show answer
valueChanges emits only on later changes. Add startWith(this.lines.value) before subscribe in the pipe, so the handler also runs once with the current value.