Coding exercise: create a search box with debounce in Angular.
Model answer
Reactive forms expose valueChanges as an observable, so RxJS operators fit naturally: debounceTime waits, distinctUntilChanged skips repeats, and switchMap cancels the older request.
@Component({
selector: 'app-search',
imports: [ReactiveFormsModule],
template: `
<input [formControl]="q" placeholder="Search" />
<ul>@for (r of results(); track r.id) { <li>{{ r.name }}</li> }</ul>`,
})
export class Search {
private http = inject(HttpClient);
q = new FormControl('', { nonNullable: true });
results = toSignal(
this.q.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap((term) => (term ? this.http.get<{ id: number; name: string }[]>('/api/search', { params: { q: term } }) : of([]))),
),
{ initialValue: [] },
);
}toSignal subscribes and unsubscribes for you, so there is no manual cleanup. switchMap is the key part: when a new term arrives, the previous request is cancelled.
Tips
- HttpClient needs provideHttpClient() in the app config.
Practise it yourself in the React and Angular code playground.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- Coding exercise: build a Todo application in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.
- Coding exercise: implement sorting and filtering in Angular.