How to Build an Accessible Combobox in Angular
In this article
This guide walks you through creating a fully accessible combobox (autocomplete) component in Angular. You'll build a text input with a dropdown list of suggestions, complete with ARIA attributes, keyboard navigation, and proper focus management, so it works for screen reader and keyboard users. You'll need a working Angular project (Angular 12 or later) and basic familiarity with components, services, and reactive forms.
What You'll Need
- An existing Angular project (created with Angular CLI)
- Basic understanding of Angular components, templates, and services
- Familiarity with TypeScript and RxJS (observables)
- No extra libraries required – we'll build it from scratch
Step-by-Step
- Generate a new component. Run
ng generate component comboboxin your terminal. This creates the component files and registers it in your module. - Define the component inputs and outputs. In
combobox.component.ts, add an@Input() options: string[]for the list of suggestions, and an@Output() selected = new EventEmitter<string>()to emit the chosen value. Also add a@ViewChildfor the input element and a reference to the dropdown list container. - Set up the template structure. In
combobox.component.html, create a wrapper<div>withclass="combobox". Inside, place an<input>element and a<ul>for the dropdown list. The list should be hidden by default (using*ngIfor a CSS class). - Add ARIA attributes to the input. On the input, set
role="combobox",aria-autocomplete="list",aria-expanded="false",aria-controls="combobox-list", andaria-activedescendant(we'll bind this to the currently highlighted option's ID). Also addaria-haspopup="listbox". - Add ARIA attributes to the list. On the
<ul>, setrole="listbox"and anid="combobox-list". For each<li>, setrole="option",id="option-0",option-1, etc., andaria-selected="false"(bind to the current selection state). - Implement the filtering logic. In the component class, create a
filteredOptions: string[]property. Use an RxJSSubjector simply a method called on(input)event that filters theoptionsarray based on the input value. Usefilter()andincludes()for case-insensitive matching. - Handle input events. In the template, bind
(input)="onInput($event)"to update the filtered list and setisOpen = true. Also bind(focus)="onFocus()"to open the dropdown if there are options, and(blur)="onBlur()"to close it (with a small delay to allow click on options). - Implement keyboard navigation. Bind
(keydown)="onKeydown($event)"on the input. HandleArrowDownandArrowUpto move theactiveIndexthrough the filtered options,Enterto select the active option,Escapeto close the dropdown, andTabto close it and move focus naturally. - Update active descendant. When
activeIndexchanges, update thearia-activedescendanton the input to the ID of the active option (e.g.,option-1). Also add a class like.activeto the active<li>for visual highlighting. - Select an option. When the user clicks an option or presses Enter, emit the selected value via
selected.emit(option), set the input value to that option, close the dropdown, and resetactiveIndexto -1. - Style the dropdown. In the component's CSS, position the
<ul>absolutely below the input, give it a border, background, and max-height with overflow-y: auto. Style the active option with a background color (e.g.,#e0e0e0). - Test with a screen reader. Use NVDA or VoiceOver to verify that the combobox announces the expanded state, the number of options, and the active option as you navigate. Ensure focus remains on the input while using arrow keys.
Common Mistakes
- Forgetting to manage focus. When the dropdown opens, focus should stay on the input, not move to the list. Use
aria-activedescendantto indicate the active option without moving focus. - Not handling blur correctly. If you close the dropdown on blur immediately, the user can't click an option. Use a
setTimeoutof 100-200ms to allow the click event to fire. - Missing ARIA attributes. Screen readers rely on
role,aria-expanded, andaria-activedescendant. Omitting them makes the component inaccessible. - Not resetting the active index. When the filtered list changes, reset
activeIndexto -1 or 0; otherwise, the highlighted option may be out of range. - Using
changeinstead ofinput. Thechangeevent fires on blur, not on each keystroke, so filtering won't update live. Use(input).
Tips
- Use a service for async data. If your options come from an API, inject a service and use
switchMapwith a debounce to avoid flooding the server. - Add a label. Always associate a
<label>with the input usingforand anid, or usearia-label. - Support mouse and touch. Add
mousedown(not click) on options to select before blur closes the list. - Keep the list short. Limit the number of visible options (e.g., 10) and scroll within the list to avoid performance issues.
- Use Angular's
trackByin*ngForto improve rendering performance.
Troubleshooting
- Dropdown doesn't open on focus. Check that
isOpenis set to true inonFocus()and that the*ngIfcondition is correct. Also ensure the input has a value or options are not empty. - Keyboard navigation doesn't work. Verify that the
(keydown)event is on the input, not the wrapper. Also check thatpreventDefault()is called for arrow keys to avoid scrolling the page. - Screen reader doesn't announce options. Ensure
aria-activedescendantis bound to a valid ID that exists in the DOM. Also verify that the list hasrole="listbox"and options haverole="option". - Click on option doesn't select. Use
(mousedown)instead of(click)because blur fires before click, closing the list. Or add a timeout in blur. - Filtering is case-sensitive. Use
toLowerCase()on both the input value and the options when filtering. - Active option is not visible when scrolling. Use
scrollIntoView()on the active element, or use CSSscroll-marginto ensure it's not hidden behind other elements.
Frequently Asked Questions
Do I need a third-party library to build an accessible combobox?
No, you can build one from scratch as shown here. Libraries like Angular Material provide ready-made components, but they add dependencies and may not match your design.
What is the difference between aria-expanded and aria-haspopup?
aria-haspopup indicates that the element has a popup (listbox, menu, etc.), while aria-expanded tells whether that popup is currently open or closed. Both are required on the input.
How do I make the combobox work with reactive forms?
Implement ControlValueAccessor on your component. This allows you to use formControlName or ngModel directly. You'll need to implement writeValue, registerOnChange, and registerOnTouched.
Why is my dropdown closing before I can click an option?
This is a common issue with blur handling. Add a setTimeout in the blur handler (e.g., 150ms) to allow the click event to fire before closing. Alternatively, use mousedown on options to select before blur.
Can I use this combobox with a remote API?
Yes, replace the local filtering with an HTTP request in a service. Use RxJS operators like debounceTime, distinctUntilChanged, and switchMap to handle async data efficiently.
How do I support multiple selection?
Multiple selection requires a different ARIA pattern (listbox with multiple selections). You'd need to add checkboxes or multi-select behavior, and use aria-multiselectable="true" on the listbox. The keyboard interaction also changes (e.g., Space to toggle).