Coding exercise: create a search box with debounce in Angular.

Angular practical coding · Freshers

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

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