Sub topic 9
Building a Debounced Search from Form valueChanges
A search box that calls the server on every keystroke wastes requests and can show results in the wrong order. This chapter builds a search-as-you-type feature from a reactive form control's valueChanges stream. Each operator in the pipeline handles one specific problem.
This chapter assumes you know Angular reactive forms (FormControl, ReactiveFormsModule) and the async pipe. It also assumes you have read the earlier chapters on HttpClient, catchError, and switchMap.
The problem with a naive search
FormControl.valueChanges is an observable that emits the control's new value after every change. If you map each value straight to an HTTP request, three problems appear:
- Request flood. Typing "angular" sends seven requests.
- Duplicate work. Typing "a", then deleting it and typing "a" again, repeats a request the user already saw.
- Out-of-order responses. The response for "ang" can arrive after the response for "angular". The screen then shows results for a term the user is no longer looking at.
The fix is a pipeline with one operator per problem.
The baseline pipeline
Here is the minimal working version:
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 } })
)
);
}nonNullable: true makes the control's type FormControl<string>. Without it the type is string | null, because reset() would set the value to null. Then term.length would not compile.
What each operator does
| Operator | Problem it solves | Behavior |
|---|---|---|
| `debounceTime(300)` | Request flood | Waits until 300 ms pass with no new value, then emits the latest value |
| `distinctUntilChanged()` | Duplicate work | Drops a value equal (`===`) to the previous emitted value |
| `filter(term => term.length >= 2)` | Useless short queries | Lets only terms of 2 or more characters through |
| `switchMap(...)` | Out-of-order responses | Unsubscribes from the previous request when a new term arrives, which cancels the HTTP call |
debounceTime throws values away. It does not delay every value. If the user types "a", "an", "ang" within 300 ms, only "ang" comes out.
Why the order matters
distinctUntilChanged must come after debounceTime. Suppose the user types "ab", pauses, then types "c" and deletes it within 300 ms. The raw stream is ab, abc, ab. Placed before the debounce, distinctUntilChanged sees three different consecutive values and passes all of them. The debounce then emits ab a second time, which repeats the request. Placed after the debounce, it compares only settled values, ab and ab, and drops the repeat.
Edge cases the baseline gets wrong
The baseline works in a demo. Four details break it in real use.
1. Clearing the box leaves stale results
filter blocks short terms, so nothing reaches switchMap when the user clears the input. The last result list stays on screen, and any in-flight request still finishes and renders. The fix is to handle short terms inside switchMap and return an empty list. Because switchMap switches to that new inner observable, it also cancels the pending request.
2. Whitespace counts as a change
"rxjs" and "rxjs " are different strings, so a trailing space triggers a new request. Apply map(term => term.trim()) before distinctUntilChanged. If your API ignores case, add .toLowerCase() as well.
3. One failed request kills the search for good
If catchError wraps the whole pipeline, the first HTTP error completes results$. The valueChanges subscription goes with it, and later keystrokes do nothing. Put catchError on the inner HTTP observable instead. Then only that one request fails, and the outer stream keeps listening.
4. No feedback while loading
Users cannot tell "no results" apart from "still loading." Model the view as an explicit state and emit a loading state first with startWith.
The production version
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {
Observable,
catchError,
debounceTime,
distinctUntilChanged,
map,
of,
startWith,
switchMap,
} from 'rxjs';
type SearchState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'done'; results: string[] }
| { status: 'error' };
const IDLE: SearchState = { status: 'idle' };
const LOADING: SearchState = { status: 'loading' };
const ERROR: SearchState = { status: 'error' };
@Component({
selector: 'app-search',
standalone: true,
imports: [ReactiveFormsModule, AsyncPipe],
template: `
<input [formControl]="query" placeholder="Search" />
@if (state$ | async; as state) {
@if (state.status === 'loading') {
<p>Searching…</p>
}
@if (state.status === 'error') {
<p>Search failed. Keep typing to try again.</p>
}
@if (state.status === 'done') {
@if (state.results.length === 0) {
<p>No matches.</p>
}
<ul>
@for (result of state.results; track result) {
<li>{{ result }}</li>
}
</ul>
}
}
`,
})
export class SearchComponent {
private http = inject(HttpClient);
query = new FormControl('', { nonNullable: true });
state$: Observable<SearchState> = this.query.valueChanges.pipe(
map(term => term.trim()),
debounceTime(300),
distinctUntilChanged(),
switchMap(term =>
term.length < 2 ? of(IDLE) : this.search(term)
)
);
private search(term: string): Observable<SearchState> {
return this.http
.get<string[]>('/api/search', { params: { q: term } })
.pipe(
map((results): SearchState => ({ status: 'done', results })),
catchError(() => of(ERROR)),
startWith(LOADING)
);
}
}Each inner observable now emits LOADING right away. It then emits either done or error. The order of operators inside search() matters. startWith sits after catchError, so the loading state is always emitted, even when the request fails. The typed IDLE, LOADING, and ERROR constants keep TypeScript from widening 'idle' to string, which would break the union type.
The async pipe owns the subscription. When the component is destroyed, the pipe unsubscribes from state$. That also unsubscribes from valueChanges and cancels any pending request, so you don't need takeUntilDestroyed here.
Further details
- No initial emission.
valueChangesemits only on change, sostate$emits nothing until the user types. If the control starts with a value, for example one restored from a query parameter, addstartWith(this.query.value)beforemap. setValuetriggers the pipeline. Callingquery.setValue('x')in code emits onvalueChanges. Pass{ emitEvent: false }when you want to update the input without running a search.- Choosing the debounce time. 200–400 ms suits most text search. Shorter values send more requests. Longer values make the UI feel slow.
- Why not
mergeMaporconcatMap?mergeMapkeeps every request alive, so the out-of-order bug comes back.concatMapqueues requests, so the user waits for results they no longer need.exhaustMapignores new terms while a request is running, which drops the term the user actually wants. - Cancellation only affects the client. Unsubscribing aborts the browser request, but the server may already be processing it. Debouncing is what reduces server load.
Exercises
Exercise
A teammate writes valueChanges.pipe(distinctUntilChanged(), debounceTime(300), switchMap(...)). The user types "ab", pauses, types "c", and deletes it within 300 ms. How many requests for "ab" are sent, and why?
Show answer
Two. Before the debounce, distinctUntilChanged sees the values "ab", "abc", and "ab". Each value differs from the one before it, so all three pass. The debounce then emits "ab" again after the second pause. Moving distinctUntilChanged after debounceTime compares only settled values and drops the repeat.
Exercise
In the baseline version, the user searches "rxjs", sees results, and then clears the input. What does the screen show, and how does the production version fix it?
Show answer
The old "rxjs" results stay visible, because filter blocks the empty term and nothing new is emitted. The production version handles short terms inside switchMap by returning of(IDLE). That replaces the displayed state and cancels any pending request.
Exercise
Why would moving catchError from search() to the end of the outer state$ pipeline be a bug?
Show answer
An error caught at the outer level replaces the whole stream with the fallback, and the stream then completes. The valueChanges subscription ends with it, so the search stops responding to typing. Catching on the inner HTTP observable limits the failure to one request.
Exercise
Inside search(), what changes if startWith(LOADING) is placed before catchError instead of after it?
Show answer
In this pipeline, the output stays the same: LOADING first, then done or error. startWith emits synchronously on subscribe, before the HTTP error can happen. Placing it last is still clearer. It shows that the loading state belongs to the whole inner stream, and it guarantees LOADING comes first even if an operator added above it throws synchronously.