Sub topic 15
Reacting to valueChanges and statusChanges
A form model is not a static object. Each keystroke, programmatic update, or validation run can change the value or status of a control, and Angular publishes those changes as RxJS observables. This chapter covers how those streams work, when they emit, and how to use them without causing memory leaks or update loops.
This chapter assumes you know basic RxJS (pipe, map, subscribe), that you can build FormControl and FormGroup instances and bind them with formGroup and formControlName, and that you know what validators and control status are.
What the two streams emit
Every AbstractControl, whether a FormControl, FormGroup, or FormArray, exposes two observables:
| Stream | Emits | Type (typed forms) |
|---|---|---|
| `valueChanges` | The control's new value, every time it is recalculated | The control's value type, for example `string` or `{ name: string; email: string }` |
| `statusChanges` | The control's new validation status | `FormControlStatus`: `'VALID'`, `'INVALID'`, `'PENDING'`, or `'DISABLED'` |
On a group, valueChanges emits the aggregated value object. Disabled children are left out of that object, the same way they are left out of form.value.
Both streams are hot and have no memory. Subscribing does not give you the current value. You get only the changes that happen after you subscribe.
The order of events during an update
All changes go through updateValueAndValidity(). Typing in an input, calling setValue, patchValue, reset, enable, or disable all trigger it. Knowing the order of steps explains most of the surprising behavior.
Two consequences follow from this order:
- Inside a child's
valueChangessubscriber,control.valueandcontrol.statusare already current. The parent'svalueandvalidare not, because the parent has not recalculated yet. - If you need the whole form's state, subscribe to the group, not the child.
A debounced search box
The most common use is reacting to typing. The following component debounces input and cleans up its subscription automatically:
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'app-search-box',
standalone: true,
imports: [ReactiveFormsModule],
template: `<input [formControl]="query" placeholder="Search" />`,
})
export class SearchBoxComponent implements OnInit {
query = new FormControl('', { nonNullable: true });
private destroyRef = inject(DestroyRef);
ngOnInit(): void {
this.query.valueChanges
.pipe(debounceTime(300), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef))
.subscribe((term) => console.log('search for', term));
}
}takeUntilDestroyed needs an injection context. In a constructor or field initializer you can call it with no arguments. In ngOnInit you must pass a DestroyRef, as shown above. If you leave out cleanup, the subscription keeps the component alive after it is destroyed, because the control outlives nothing on its own but the closure holds the component.
If the search calls an HTTP API, put switchMap after distinctUntilChanged so that a new term cancels the request still in flight.
Dependent fields and getting the initial value
A typical case is one field controlling another: changing the country clears the region and enables or disables it. Because valueChanges does not replay the current value, use startWith so the logic also runs once at startup.
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { startWith } from 'rxjs/operators';
@Component({
selector: 'app-address-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form">
<select formControlName="country">
<option value="">Choose a country</option>
<option value="US">United States</option>
<option value="CA">Canada</option>
</select>
<input formControlName="region" placeholder="State or province" />
<p>Form status: {{ status() }}</p>
</form>
`,
})
export class AddressFormComponent implements OnInit {
form = new FormGroup({
country: new FormControl('', { nonNullable: true, validators: [Validators.required] }),
region: new FormControl('', { nonNullable: true, validators: [Validators.required] }),ignal(this.form.statusChanges, { initialValue: this.form.status });
private destroyRef = inject(DestroyRef);
ngOnInit(): void { = this.form.controls;
country.valueChanges
.pipe(startWith(country.value), takeUntilDestroyed(this.destroyRef))
.subscribe((value) => {
region.reset();
if (value) {
region.enable();
} else {
region.disable();
}
});
}
}toSignal subsubscribes when the component is destroyed. The initialValue option fills the gap caused by the stream having no memory. The status signal is useful for template indicators such as a "Checking…" label while async validators leave the form in PENDING.
Programmatic changes and feedback loops
valueChanges also emits when your own code calls setValue or patchValue. That causes trouble when two controls update each other:
import { FormControl, FormGroup } from '@angular/forms';
const temps = new FormGroup({
celsius: new FormControl(0, { nonNullable: true }),
fahrenheit: new FormControl(32, { nonNullable: true }),
});
const { celsius, fahrenheit } = temps.controls;
celsius.valueChanges.subscribe((c) =>
fahrenheit.setValue((c * 9) / 5 + 32, { emitEvent: false }),
);
fahrenheit.valueChanges.subscribe((f) =>
celsius.setValue(((f - 32) * 5) / 9, { emitEvent: false }),
);
celsius.setValue(100);
console.log(fahrenheit.value); // 212Without { emitEvent: false }, each update triggers the other subscriber, and the two keep firing at each other until rounding errors happen to settle or the stack overflows. With the option set, the value and validity still update, but neither valueChanges nor statusChanges emits for that call.
Related options for setValue, patchValue, reset, enable, and disable:
| Option | Effect |
|---|---|
| `emitEvent: false` | Updates state without emitting on either stream |
| `onlySelf: true` | Updates this control but does not recalculate its ancestors |
Use onlySelf carefully. It leaves the parent's value and valid stale until something else recalculates them.
The unified events stream
Since Angular 18, every control also has an events observable. It emits typed event objects: ValueChangeEvent, StatusChangeEvent, TouchedChangeEvent, PristineChangeEvent, and, on the root group, FormSubmittedEvent and FormResetEvent. This stream is the only one that reports touched and dirty changes, which valueChanges and statusChanges never do.
import { FormControl, TouchedChangeEvent } from '@angular/forms';
import { filter } from 'rxjs/operators';
const email = new FormControl('', { nonNullable: true });
email.events
.pipe(filter((e): e is TouchedChangeEvent => e instanceof TouchedChangeEvent))
.subscribe((e) => console.log('touched:', e.touched));
email.markAsTouched(); // logs "touched: true"Common mistakes
- Expecting an initial emission. Add
startWith(control.value)or givetoSignalaninitialValue. - Forgetting cleanup. Use
takeUntilDestroyed,toSignal, or theasyncpipe. A baresubscribein a component leaks. - Subscribing before the control exists. If the template or code replaces a control with
setControl, subscriptions on the old instance stop receiving anything. Subscribe to the parent group, or subscribe again after replacing. - Expensive work on every keystroke. Debounce it, or use
updateOn: 'blur', which the next chapter covers. - Missing disabled fields. A disabled child is not in the group's emitted value. Call
getRawValue()if you need it.
Exercise
Inside a subscription to form.controls.email.valueChanges, you log this.form.valid and see false even though the email you just typed makes the whole form valid. Why, and how do you fix it?
Show answer
The child emits valueChanges before it calls updateValueAndValidity on its parent, so the group's validity has not been recalculated yet. Subscribe to this.form.statusChanges (or this.form.valueChanges) instead, or read the group's state somewhere that runs after the parent has updated.
Exercise
A component subscribes to country.valueChanges to enable the region field, but when the form loads with country already set to "US", the region stays disabled until the user picks the country again. What is missing?
Show answer
valueChanges does not emit the current value on subscription. Add startWith(country.value) to the pipe so the handler runs once with the starting value.
Exercise
Two controls, price and priceWithTax, keep each other in sync through valueChanges subscriptions that call setValue. The browser freezes when the user types. What change stops the loop while keeping both values correct?
Show answer
Pass { emitEvent: false } to the setValue calls inside the subscribers. The target control still updates its value and validity, but it does not emit valueChanges, so the other subscriber is not triggered again.