← Back to Angular, page 4

angular-0080 · Medium mid

Build an accessible typeahead (autocomplete) with a reactive form control. How do you handle debounce, cancellation, keyboard navigation and ARIA roles?

Drive the search from the control's valueChanges with debounceTime, distinctUntilChanged and switchMap, show results in a listbox, and keep the active option in a signal. For accessibility use role combobox on the input with aria-expanded, aria-controls and aria-activedescendant, support ArrowUp, ArrowDown, Enter and Escape, and announce the result count.

Full answer

A typeahead looks small but combines streams, state, and accessibility.

Data flow:

  1. control.valueChanges emits as the user types.
  2. debounceTime(250) waits for a pause, map(trim) and distinctUntilChanged() skip no-ops.
  3. switchMap calls the search and cancels the previous call, so slow old responses cannot overwrite newer ones. Put catchError inside it so one failure does not end the stream. Return of([]) for terms shorter than two characters.
  4. A loading flag can be set with tap before switchMap and cleared afterwards. The final stream becomes a signal with toSignal.

UI state in signals: open, activeIndex, and the results. A selection writes the chosen value into the control and closes the list.

ARIA pattern (WAI-ARIA combobox with listbox popup):

  • The input has role="combobox", aria-expanded, aria-controls="listbox-id", aria-autocomplete="list", and aria-activedescendant set to the id of the active option.
  • The list has role="listbox", and each option has role="option", a unique id, and aria-selected.
  • Focus stays in the input. The "active" option is a visual and ARIA state only.
  • Keys: ArrowDown and ArrowUp move the active option (wrap or stop, and open the list if closed), Enter selects, Escape closes, and Tab closes without selecting.
  • Announce results with a live region: "5 results available".

Edge cases: empty results ("No matches"), clicking an option must not blur the input before the click is handled (use mousedown or prevent default), the list closes on blur with a short delay, and typing must reset the active index.

For production use, Angular Material's autocomplete or the CDK listbox gives tested keyboard and ARIA behaviour. Building it yourself shows that you understand what they do.

typescript
import { Component, computed, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { Observable, catchError, debounceTime, delay, distinctUntilChanged, map, of, switchMap, tap } from 'rxjs';

const COURSES = ['Angular basics', 'Angular signals', 'Angular testing', 'RxJS in practice', 'TypeScript essentials'];

function searchCourses(term: string): Observable<string[]> {
  const q = term.toLowerCase();
  return of(COURSES.filter((c) => c.toLowerCase().includes(q))).pipe(delay(100));
}

@Component({
  selector: 'app-course-typeahead',
  imports: [ReactiveFormsModule],
  template: `
    <label for="course-search">Course</label>
    <input
      id="course-search"
      type="text"
      autocomplete="off"
      role="combobox"
      aria-autocomplete="list"
      aria-controls="course-listbox"
      [attr.aria-expanded]="isOpen()"
      [attr.aria-activedescendant]="activeId()"
      [formControl]="control"
      (keydown)="onKey($event)"
      (blur)="open.set(false)"
    />

    <ul id="course-listbox" role="listbox" [hidden]="!isOpen()">
      @for (item of results(); track item; let i = $index) {
        <li
          role="option"
          [id]="'course-option-' + i"
          [attr.aria-selected]="i === activeIndex()"
          [class.active]="i === activeIndex()"
          (mousedown)="$event.preventDefault(); choose(item)"
        >
          {{ item }}
        </li>
      }
    </ul>

    <p class="visually-hidden" aria-live="polite">{{ status() }}</p>
  `,
  styles: `
    .active { background: #dbe8ff; }
    .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
  `,
})
export class CourseTypeaheadComponent {
  readonly control = new FormControl('', { nonNullable: true });
  readonly open = signal(false);
  readonly activeIndex = signal(-1);
  readonly loading = signal(false);

  readonly results = toSignal(
    this.control.valueChanges.pipe(
      debounceTime(250),
      map((v) => v.trim()),
      distinctUntilChanged(),
      tap(() => this.activeIndex.set(-1)),
      switchMap((term) => {
        if (term.length < 2) {
          this.open.set(false);
          return of<string[]>([]);
        }
        this.loading.set(true);
        return searchCourses(term).pipe(
          catchError(() => of<string[]>([])),
          tap(() => {
            this.loading.set(false);
            this.open.set(true);
          }),
        );
      }),
    ),
    { initialValue: [] as string[] },
  );

  readonly isOpen = computed(() => this.open() && !this.loading());
  readonly activeId = computed(() => (this.activeIndex() >= 0 ? `course-option-${this.activeIndex()}` : null));
  readonly status = computed(() => (this.isOpen() ? `${this.results().length} results available` : ''));

  onKey(event: KeyboardEvent): void {
    const count = this.results().length;
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault();
        this.open.set(count > 0);
        this.activeIndex.update((i) => (i + 1) % Math.max(count, 1));
        break;
      case 'ArrowUp':
        event.preventDefault();
        this.activeIndex.update((i) => (i <= 0 ? count - 1 : i - 1));
        break;
      case 'Enter': {
        const item = this.results()[this.activeIndex()];
        if (this.isOpen() && item) {
          event.preventDefault();
          this.choose(item);
        }
        break;
      }
      case 'Escape':
        this.open.set(false);
        break;
    }
  }

  choose(item: string): void {
    this.control.setValue(item, { emitEvent: false });
    this.open.set(false);
  }
}

Angular 20.3, strict template check passes, and a Karma test checks the arrow-key and Enter behaviour. The search function is a local fake with a 100 ms delay.

Key points

  • `valueChanges` with `debounceTime`, `distinctUntilChanged`, and `switchMap` (and an inner `catchError`).
  • State in signals: results, `open`, and `activeIndex`.
  • ARIA: combobox input, listbox, options, and `aria-activedescendant`. Focus stays in the input.
  • Keys: arrows, Enter, Escape. Announce the result count.

Common mistakes

  • Using `mergeMap`, so old slow responses overwrite new ones.
  • Moving real focus into options, which breaks typing.
  • Closing the list on blur before the click on an option is processed.

Follow-ups

  • How would you cache previous searches?
  • How would you highlight the matching part of each result?
  • Why use `aria-activedescendant` and not moving focus?

Tips

  • Walk through the stream first, then the ARIA pattern.
  • Name the click-versus-blur race. It shows hands-on experience.
  • Say when you would use Material's autocomplete instead.

Evaluation rubric

  • Builds a correct debounced and cancelled stream.
  • Implements keyboard behaviour and ARIA roles.
  • Covers edge cases.