Autocomplete Search Bar (Standalone Component)
FormControl + ReactiveFormsModule)valueChanges, debounce, switchMap)toSignalRequirements
Use a standalone Angular component as the root component. Use ReactiveFormsModuleand aFormControlfor the input binding.Show a dropdown of suggestions filtered by the current query (case-insensitive, substring match). Debounce input changes (e.g. 250–400ms) before searching. Support mouse selection (mousedown on a suggestion sets the input value and closes dropdown). Support keyboard navigation: ArrowDown/ArrowUp moves active option, Enter selects, Escape closes. Close the dropdown when clicking outside the component. Basic accessibility: use role="combobox",role="listbox",role="option", plusaria-expandedandaria-activedescendant.
What the checks look for
The checks find elements by control labelled "Search", option, listbox, body, combobox. Keep these in your markup.
Expected behavior
Typing updates suggestions after the debounce delay. If query is empty/whitespace, dropdown is closed and no suggestions are shown. ArrowDown from no selection activates the first option; ArrowUp activates the last option. Enter selects the active option (if any) and closes the dropdown. Escape closes the dropdown without changing the input. Clicking outside closes the dropdown.
Implementation notes
Create a fake async search function search(q)that filters a local dataset and returnsof(filtered).pipe(delay(...)).Build the results stream from queryControl.valueChangeswithdebounceTime+distinctUntilChanged+switchMapintosearch().Bridge the stream to the template with toSignaland read it asresults(); like theasyncpipe, it needs no imperative subscription.Keep isOpenandactiveIndexin signals. The stream'stapsets them in a debounce timer callback, which no template event covers, so anOnPushview only notices through a signal write.Keep the solution in a single component (no need for services).
Solution idea
Bind the input to queryControl, a FormControl, with [formControl], and build the search from its valueChanges: typing and select() both set the control's value, so one stream sees every query. The stream trims the text, waits with debounceTime(300), drops repeats with distinctUntilChanged(), and switchMaps into a fake async search() that filters a local list of cities and answers after delay(150). toSignal turns the stream into the results signal the template reads. isOpen and activeIndex are signals for dropdown visibility and keyboard navigation, and a document:mousedown listener in the component's host metadata closes the list when the click lands outside the component.
Public interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- Code360: Booking.com frontend engineer interview experience, April 2023
One account describes a 40-minute round with three engineers: create an autocomplete text box in vanilla JavaScript, HTML and CSS, covering edge cases and must-haves versus nice-to-haves. This starter is a practice version in Angular; the reported round was framework-free.
- enginebogie: Booking.com frontend engineer machine-coding round, May 2023
One account describes a 60-minute machine-coding round: a typeahead with API calls, a live dropdown, highlighted matches, debounce or throttle, caching, keyboard navigation and error states. This starter is a practice version of that round in Angular, not its reported wording.
Reported in a public Booking.com interview account. Booking.com frontend interview questions
Solution
Overview
Bind the input to queryControl, a FormControl, with [formControl], and build the search from its valueChanges: typing and select() both set the control's value, so one stream sees every query. The stream trims the text, waits with debounceTime(300), drops repeats with distinctUntilChanged(), and switchMaps into a fake async search() that filters a local list of cities and answers after delay(150). toSignal turns the stream into the results signal the template reads. isOpen and activeIndex are signals for dropdown visibility and keyboard navigation, and a document:mousedown listener in the component's host metadata closes the list when the click lands outside the component.
Test cases
- Type "san" → after debounce, suggestions include "San Francisco" / "San Jose".
- Type "" (empty) → dropdown closes, no results shown.
- ArrowDown twice → activeIndex changes accordingly.
- Enter on active option → input becomes that value, dropdown closes.
- Escape → dropdown closes.
- Click outside → dropdown closes.
- Mouse down on an option → selects it and closes.
valueChanges-driven results signal + keyboard navigation + outside click close
1) Create queryControl = new FormControl('', { nonNullable: true }) and bind it with [formControl]. query = toSignal(queryControl.valueChanges, ...) gives the highlight the current text.
2) Build results with toSignal from queryControl.valueChanges:
- startWith(queryControl.value)
- map(v => v.trim())
- debounceTime(300)
- distinctUntilChanged()
- tap(q => ...) opens the list for a typed query, keeps it closed for a pick (q !== pickedValue), and resets activeIndex
- switchMap(q => q ? search(q) : of([]))
3) onInput() clears pickedValue, so typed text is a new search even when it equals the last pick. select(value) sets pickedValue, calls setValue(value) and closes the list.
4) onKeyDown: Escape closes; ArrowDown/ArrowUp move activeIndex with wrap-around through activeIndex.update(...), and on a closed list the first arrow key only opens it; Enter selects the active option.
5) Close on outside click with '(document:mousedown)' in the host metadata and ElementRef.contains.
6) Use (mousedown) on options so the pick happens before the input blurs.
isOpen and activeIndex are signals because tap sets them on a timer, after the input event; under OnPush, a plain field set there would wait for some other change to refresh the view. With a 300ms debounce and a 150ms search, a newer query never reaches switchMap while an older search is still running, so here switchMap starts to matter once search() is slower than the debounce, as a real request can be.
Files
{
"name": "angular-autocomplete-search",
"private": true
}
{
"compilerOptions": {
"target": "es2022",
"strict": true,
"noEmitOnError": false
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Angular SDK • Autocomplete</title>
</head>
<body>
<app-root></app-root>
</body>
</html>
import 'zone.js';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent).catch(console.error);
:root {
color-scheme: dark;
}
html,body {
margin: 0;
height: 100%;
background: #0a0a0a;
}
body {
font-family: system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
}
.page {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
background: #0a0a0a;
color: #e5e7eb;
font-family: system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;
}
.card {
width: 100%;
max-width: 520px;
background: #0b1020;
border: 1px solid #1f2937;
border-radius: 14px;
padding: 18px;
display: grid;
gap: 14px;
}
.title {
margin: 0;
font-size: 18px;
font-weight: 800;
}
.label {
display: block;
font-size: 12px;
color: #9ca3af;
margin-bottom: 6px;
}
.combo {
position: relative;
}
.input {
width: 100%;
padding: 12px 12px;
border-radius: 12px;
border: 1px solid #374151;
background: #0a0f1e;
color: #e5e7eb;
outline: none;
}
.input:focus {
border-color: #a3e635;
box-shadow: 0 0 0 2px rgba(163,230,53,.15);
}
.list {
position: absolute;
z-index: 10;
left: 0;
right: 0;
margin-top: 8px;
max-height: 240px;
overflow: auto;
border-radius: 12px;
border: 1px solid #1f2937;
background: #0a0f1e;
}
.option {
padding: 10px 12px;
cursor: pointer;
border-bottom: 1px solid rgba(31,41,55,.5);
}
.option:last-child {
border-bottom: none;
}
.option.active {
background: rgba(163,230,53,.12);
}
.empty {
padding: 10px 12px;
color: #9ca3af;
}
.hint {
margin: 0;
color: #9ca3af;
font-size: 12px;
}
mark {
background: rgba(163,230,53,.25);
color: #e5e7eb;
border-radius: 4px;
padding: 0 2px;
}
<main class="page">
<section class="card">
<h1 class="title">Autocomplete</h1>
<div
class="combo"
role="combobox"
aria-haspopup="listbox"
[attr.aria-expanded]="isOpen()"
[attr.aria-owns]="listboxId"
[attr.aria-activedescendant]="activeIndex() >= 0 ? optionId(activeIndex()) : null"
>
<label class="label" for="q">Search</label>
<input
id="q"
class="input"
type="text"
autocomplete="off"
placeholder="Type a city..."
[formControl]="queryControl"
(input)="onInput()"
(focus)="onFocus()"
(keydown)="onKeyDown($event)"
/>
@if (results(); as list) {
@if (isOpen()) {
<ul class="list" role="listbox" [id]="listboxId">
@for (item of list; track item; let i = $index) {
<li
class="option"
role="option"
[id]="optionId(i)"
[class.active]="i === activeIndex()"
[attr.aria-selected]="i === activeIndex()"
(mousedown)="select(item)"
[innerHTML]="highlight(item, query())"
></li>
}
@if (list.length === 0) {
<li class="empty">No results</li>
}
</ul>
}
}
</div>
<p class="hint">Keyboard: ↑/↓ navigate, Enter select, Esc close.</p>
</section>
</main>
import { ChangeDetectionStrategy, Component, ElementRef, inject, signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { of } from 'rxjs';
import { debounceTime, delay, distinctUntilChanged, map, startWith, switchMap, tap } from 'rxjs/operators';
@Component({
selector: 'app-root',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
host: {
'(document:mousedown)': 'onDocMouseDown($event)'
}
})
export class AppComponent {
private readonly host = inject(ElementRef<HTMLElement>);
readonly listboxId = 'autocomplete-listbox';
private readonly cities: string[] = [
'Amsterdam', 'Ankara', 'Athens', 'Austin',
'Barcelona', 'Berlin', 'Boston', 'Brussels',
'Chicago', 'Copenhagen',
'Dubai',
'Edinburgh',
'Frankfurt',
'Hamburg',
'Istanbul', 'Izmir',
'London', 'Los Angeles',
'Madrid', 'Miami', 'Milan', 'Munich',
'New York',
'Oslo',
'Paris', 'Prague',
'Rome',
'San Diego', 'San Francisco', 'San Jose', 'Seattle',
'Tokyo',
'Vienna',
'Zurich'
];
readonly queryControl = new FormControl('', { nonNullable: true });
readonly query = toSignal(this.queryControl.valueChanges, { initialValue: this.queryControl.value });
readonly isOpen = signal(false);
readonly activeIndex = signal(-1);
private pickedValue: string | null = null;
// Typing (via [formControl]) and select() both set the control, so valueChanges carries every query.
readonly results = toSignal(
this.queryControl.valueChanges.pipe(
startWith(this.queryControl.value),
map((v: string) => v.trim()),
debounceTime(300),
distinctUntilChanged(),
tap((q: string) => {
// A pick fills the input, but it is not a new search.
this.isOpen.set(!!q && q !== this.pickedValue);
this.activeIndex.set(-1);
}),
switchMap((q: string) => (q ? this.search(q) : of([] as string[])))
)
);
onInput(): void {
this.pickedValue = null;
}
onFocus(): void {
if (this.queryControl.value.trim()) this.isOpen.set(true);
}
onKeyDown(ev: KeyboardEvent): void {
if (ev.key === 'Escape') {
this.isOpen.set(false);
this.activeIndex.set(-1);
return;
}
// On a closed list the first arrow key only opens it: its options are not in the DOM until the next render.
if (!this.isOpen() && (ev.key === 'ArrowDown' || ev.key === 'ArrowUp')) {
this.isOpen.set(!!this.queryControl.value.trim());
}
const options = this.host.nativeElement.querySelectorAll('[role="option"]');
const len = options.length;
if (!this.isOpen() || len === 0) return;
if (ev.key === 'ArrowDown') {
ev.preventDefault();
this.activeIndex.update((i) => (i < 0 ? 0 : (i + 1) % len));
return;
}
if (ev.key === 'ArrowUp') {
ev.preventDefault();
this.activeIndex.update((i) => (i < 0 ? len - 1 : (i - 1 + len) % len));
return;
}
if (ev.key === 'Enter') {
const index = this.activeIndex();
if (index >= 0 && index < len) {
ev.preventDefault();
const el = options[index] as HTMLElement;
this.select(el.textContent ?? '');
}
}
}
select(value: string): void {
this.pickedValue = value;
this.queryControl.setValue(value);
this.isOpen.set(false);
this.activeIndex.set(-1);
}
optionId(i: number): string {
return `opt-${i}`;
}
highlight(item: string, queryRaw: unknown): string {
const q = String(queryRaw ?? '').trim();
if (!q) return this.escapeHtml(item);
const idx = item.toLowerCase().indexOf(q.toLowerCase());
if (idx < 0) return this.escapeHtml(item);
const before = this.escapeHtml(item.slice(0, idx));
const mid = this.escapeHtml(item.slice(idx, idx + q.length));
const after = this.escapeHtml(item.slice(idx + q.length));
return `${before}<mark>${mid}</mark>${after}`;
}
onDocMouseDown(ev: MouseEvent): void {
const target = ev.target as Node | null;
if (!target) return;
if (!this.host.nativeElement.contains(target)) {
this.isOpen.set(false);
this.activeIndex.set(-1);
}
}
private search(q: string) {
const needle = q.toLowerCase();
const filtered = this.cities
.filter((c) => c.toLowerCase().includes(needle))
.slice(0, 8);
return of(filtered).pipe(delay(150));
}
private escapeHtml(s: string): string {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
}
Notes & Pitfalls
Forgetting debounceTime+switchMap(can cause too many searches and stale results).Not trimming the query (whitespace should behave like empty). Using (click)on options (can lose selection due to event ordering when the input blurs).Not handling wrap-around behavior for arrow navigation. Missing ARIA roles/attributes, making it harder for assistive tech. Reopening the dropdown after a pick: filling the input with the picked city is not a new search. Setting isOpenoractiveIndexas plain fields in the stream'stapof anOnPushcomponent: the timer callback does not mark the view, so the list opens only when something else refreshes it.
Drive the RxJS pipeline from queryControl.valueChanges, which reports both typed text andsetValuepicks.Bridge the results stream to the template with toSignalinstead of theasyncpipe.Keep dropdown state ( isOpen,activeIndex) in signals and moveactiveIndexwithupdate.Listen to document:mousedownthrough the component'shostmetadata to close on outside click.Wrap-around navigation using modulo arithmetic.
Common mistakes on this challenge
Fix the Angular template compilation contract first
Framework assertions cannot be trusted until the standalone component and its modern control-flow template compile and boot. Fix the first Angular compiler diagnostic, then check every @if,@for, or@switchblock for balanced braces and a validtrackexpression.Verify standalone importsincludes the forms modules, directives, or pipes the template actually uses; built-in control flow alone does not requireCommonModule.Wait for the preview to boot successfully before debugging assertion mismatches, then re-run one behavior check at a time.
Call a signal where the template reads it
The page shows a "[Signal: …]" label, which Angular prints when a template reads a signal without calling it. Write count()rather thancountin interpolations: a signal is a function, and the template needs its value.Check property bindings as well: [disabled]="isEmpty"binds the function, which is always truthy, while[disabled]="isEmpty()"binds the boolean.Inputs, models and computed values read the same way, for example rating(),value()orfilteredUsers()inside@for.
A pick or an outside click must close the dropdown for good
Filling the input with the picked city looks like a new query, so a debounced search can reopen the dropdown after it closed. Mark the picked value, then skip opening the dropdown when the search stream or watcher sees that same value. Clear the mark on the next real input event so typing still opens the dropdown. Listen for mousedown on the document and close only when the target is outside the component.
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.