Sub topic 9
Building a Debounced Search from Form valueChanges
This chapter assumes you know reactive forms (FormControl, ReactiveFormsModule), the async pipe, and how switchMap cancels an earlier inner observable when a new value arrives. Here those pieces come together in a search box that sends few requests and never shows stale results.
The problem with raw keystrokes
A FormControl exposes valueChanges, an observable that emits the control's value every time it changes. Typing "angular" produces seven emissions. If each emission started an HTTP request, you would send seven requests. They might also come back out of order, so an old result for "ang" could overwrite the newer result for "angular".
A debounced search cuts this noise down in stages before any request is sent.
The component
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs';
@Component({
selector: 'app-search',
standalone: true,
imports: [ReactiveFormsModule, AsyncPipe],
template: `
<input [formControl]="query" placeholder="Search" />
@if (results$ | async; as results) {
<ul>
@for (result of results; track result) {
<li>{{ result }}</li>
}
</ul>
}
`,
})
export class SearchComponent {
private http = inject(HttpClient);
query = new FormControl('', { nonNullable: true });
results$ = this.query.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
switchMap(term =>
this.http.get<string[]>('/api/search', { params: { q: term } })
)
);
}What each operator does
| Operator | Role in the search |
|---|---|
| `debounceTime(300)` | Waits until the user stops typing for 300 ms, then emits only the latest value |
| `distinctUntilChanged()` | Drops a value that equals the previous one, such as "cat" → "cats" → "cat" settling back on "cat" |
| `filter(term => term.length >= 2)` | Skips terms too short to search |
| `switchMap(...)` | Starts a request and cancels any request still in flight |
Order matters. Put debounceTime first so that distinctUntilChanged compares settled values rather than each keystroke. nonNullable: true types the value as string, so term.length compiles without null checks.
The async pipe subscribes when the component renders and unsubscribes when it is destroyed. Leaving the component therefore also cancels any request that is still pending.
Common errors
- Using
mergeMapinstead ofswitchMap. Every request runs to completion, and a slow early response can replace newer results. - Letting one HTTP error kill the search. If a request fails inside
switchMapwith no handler, the error reaches the outer stream and the search stops for good. PutcatchError(() => of([]))on the innerhttp.get(...)so that only that one request fails. - Stale results after clearing the box.
filterdrops short terms, so the last list stays on screen. If clearing the box should clear the results, remove thefilterand decide insideswitchMapinstead. - Subscribing manually and assigning to a field. Without an unsubscribe this leaks. Use the async pipe as shown.
Exercise
Change results$ so that terms shorter than two characters produce an empty list instead of keeping the old results, and so that a failed request shows an empty list without stopping the search.
Show answer
Remove the filter and branch inside switchMap: switchMap(term => term.length < 2 ? of([]) : this.http.get<string[]>('/api/search', { params: { q: term } }).pipe(catchError(() => of([])))). Import of and catchError from 'rxjs'. Because catchError sits on the inner observable, an error replaces only that one response and valueChanges keeps emitting.
Exercise
A user types "rx", pauses 400 ms, types "j", then deletes it within 100 ms. How many requests are sent?
Show answer
One. "rx" settles after 300 ms and sends a request. "rxj" followed by "rx" inside the debounce window settles on "rx", and distinctUntilChanged drops it because it equals the previous value.