Sub topic 13
Reacting to changes with valueChanges
This chapter assumes you can build a FormArray of FormGroups, bind it with formArrayName and [formGroupName], and add or remove rows. It also assumes you know basic RxJS: subscribe, pipe, map. By the end you will know when a FormArray emits, what it emits, and how to react without creating loops, stale reads or leaked subscriptions.
What valueChanges is
Every control, whether a FormControl, FormGroup or FormArray, has a valueChanges observable. It emits the control's new value each time that value is recalculated. For a FormArray the emitted value is an array with one entry per child, and each entry is that child's value.
There are three details to remember:
- It does not emit on subscribe. If you need the current value too, add
startWith. - The emitted value leaves out disabled children. Call
getRawValue()on the control when you need everything. - Related to
valueChanges,statusChangesemitsVALID,INVALID,PENDINGorDISABLEDwhenever validity is recomputed.
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { NonNullableFormBuilder } from '@angular/forms';
@Component({
selector: 'app-email-list',
standalone: true,
template: ``,
})
export class EmailListComponent {
private fb = inject(NonNullableFormBuilder);
emails = this.fb.array(['[email protected]']);
constructor() {
this.emails.valueChanges
.pipe(takeUntilDestroyed())
.subscribe((value) => console.log('emails changed', value));
}
}takeUntilDestroyed() with no argument works only in an injection context such as a constructor or field initializer. Elsewhere, pass a DestroyRef: takeUntilDestroyed(this.destroyRef).
What triggers an emission
Structural changes count as value changes. push, insert, removeAt, setControl and clear all recalculate the array's value, so subscribers are notified.
| Action | Emits on the array? |
|---|---|
| User types in a row's input | Yes |
| `push`, `insert`, `removeAt`, `clear` | Yes |
| `setValue`, `patchValue` on a child or the array | Yes |
| `disable()` or `enable()` on a child | Yes |
| `reset()` | Yes |
| Any of the above with `{ emitEvent: false }` | No |
| Marking a control touched | No |
The order of emissions
A change starts at the leaf control and travels up through each parent. The diagram shows what happens when a user types into one input.
This order has a practical consequence. Inside a child's subscription, the parent's value has not been recalculated yet. If you subscribe to a single row control and read this.form.value in the callback, you get the old data. Subscribe to the array, or to the group, when you need a consistent view of the whole list.
Example: a live total
An order form with price and quantity per row needs a total that follows every edit, add and remove. One subscription on the array covers all three cases.
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { map, startWith } from 'rxjs';
@Component({
selector: 'app-lines',
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 formControlName="name" placeholder="Name" />
<input type="number" formControlName="price" />
<input type="number" formControlName="quantity" />
<span>{{ line.controls.lineTotal.value.toFixed(2) }}</span>
<button type="button" (click)="remove(i)">Remove</button>
</div>
}
</div>
<button type="button" (click)="add()">Add line</button>
<p>Total: {{ total().toFixed(2) }}</p>
</form>
`,
})
export class LinesComponent {
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
lines: this.fb.array([this.createLine()]),
});
get lines() {
return this.form.controls.lines;
}
total = toSignal(
this.lines.valueChanges.pipe(
startWith(null),
map(() => this.computeTotal()),
),
{ requireSync: true },
);
constructor() {
this.lines.valueChanges.pipe(takeUntilDestroyed()).subscribe(() => {
for (const group of this.lines.controls) {
const { price, quantity } = group.getRawValue();
group.controls.lineTotal.setValue((price ?? 0) * (quantity ?? 0), { emitEvent: false });
}
});
}
createLine() {
return this.fb.group({
name: ['', Validators.required],
price: [0, Validators.min(0)],
quantity: [1, Validators.min(1)],
lineTotal: [{ value: 0, disabled: true }],
});
}
add() {
this.lines.push(this.createLine());
}
remove(index: number) {
this.lines.removeAt(index);
}
private computeTotal() {
return this.lines
.getRawValue()
.reduce((sum, l) => sum + (l.price ?? 0) * (l.quantity ?? 0), 0);
}
}Several choices in this component are deliberate:
startWith(null)makes the stream emit once on subscribe. That is whytoSignalcan userequireSync: trueand return a plainnumbersignal.getRawValue()includes the disabledlineTotalcontrol. The plainvaluewould omit it.price ?? 0guards against an empty number input. Angular's number accessor writesnullfor an empty field, even though a non-nullable control is typed asnumber.computeTotaluses price and quantity, notlineTotal. ThetoSignalsubscription is registered before the constructor's subscription. At the time it runs,lineTotalhas not been updated yet.
Avoiding feedback loops with emitEvent
The constructor subscription writes back into the form it is listening to. Without { emitEvent: false }, each setValue would trigger another array emission, which would call the subscriber again, forever.
emitEvent: false suppresses valueChanges and statusChanges on the control and on its ancestors. The value and validity of every ancestor are still recalculated. Only the notification is skipped. This is also why the order of subscriptions matters, as the previous section showed.
Loading data without a storm of emissions
Each push into the array emits. Loading 200 rows by calling push 200 times runs your subscribers 200 times. Suppress the individual events and notify once at the end.
setLines(data: { name: string; price: number; quantity: number }[]) {
this.lines.clear({ emitEvent: false });
for (const d of data) {
const group = this.createLine();
group.patchValue(d);
this.lines.push(group, { emitEvent: false });
}
this.lines.updateValueAndValidity();
}The final updateValueAndValidity() recalculates the array and its parents and emits one valueChanges. This method sits inside the component class from the previous example, so it can use this.lines and this.createLine().
Debouncing and filtering
Typing fires valueChanges on every keystroke. For work that is expensive, such as a server call to check whether a code exists, add debounceTime.
this.lines.valueChanges
.pipe(debounceTime(300), takeUntilDestroyed(this.destroyRef))
.subscribe((rows) => this.save(rows));Be careful with distinctUntilChanged. The array emits a new array object each time, so the default reference comparison never filters anything. Supply a comparator, for example one that compares JSON.stringify output, or compare a derived primitive such as the total.
Subscribing per row
You can subscribe to one row, for example row.controls.quantity.valueChanges. The subscription stays active after removeAt, because nothing completes it. The control stops emitting, but your closure keeps it in memory until the subscription ends. If you use per-row subscriptions, give each one a takeUntil tied to that row's removal, or prefer a single subscription at the array level as in the example above.
Subscribing to all events
From Angular 18, every control also exposes an events observable. It emits typed objects such as ValueChangeEvent, StatusChangeEvent, TouchedChangeEvent, PristineChangeEvent, FormSubmittedEvent and FormResetEvent. Each event carries a source property that names the control that originated it. Use events when you need to react to touched or pristine state, which valueChanges never reports.
Common mistakes
- Expecting an initial emission, and so never rendering the first state. Add
startWith. - Reading the parent's
valueinside a child's subscription and seeing stale data. - Writing to the form inside a subscription without
emitEvent: false. - Using
valueand missing disabled controls. UsegetRawValue(). - Calling
subscribein a constructor orngOnInitwith no teardown. UsetakeUntilDestroyed.
Exercise
A component subscribes to this.form.controls.lines.valueChanges and, in the callback, calls this.form.controls.lines.at(0).controls.price.setValue(10). What happens, and how do you fix it?
Show answer
Each setValue makes the row group and then the array emit again, so the callback runs again and calls setValue again, which loops without end. Pass { emitEvent: false } to the setValue call. The value and validity still update, but no new emission reaches the subscriber.
Exercise
You call lines.push(group) 50 times in a loop to load saved data, and your valueChanges subscriber, which posts to a server, runs 50 times. How can you make it run once?
Show answer
Clear the array with clear({ emitEvent: false }) and push each group with { emitEvent: false }. After the loop, call lines.updateValueAndValidity() once, which emits a single valueChanges.
Exercise
Why does distinctUntilChanged() with no arguments fail to filter repeated FormArray emissions, and what can you do instead?
Show answer
FormArray.valueChanges emits a new array object each time, and the default comparator checks reference equality, so every emission looks different. Pass a custom comparator, for example comparing JSON.stringify of both values, or map the stream to a primitive such as the total and apply distinctUntilChanged to that.