HeadlessCombobox

Angular
@pdanpdan/headless-combobox-angular

A signals store. Call injectCombobox from an injection context and read combobox.snapshot() in the template. Angular gets a store rather than a render-prop component.

Install

pnpm add @pdanpdan/headless-combobox-angular

Binding

There is no Angular component wrapper. The store exposes the same state, actions, and ref setters through its snapshot signal.

readonly value = signal<User | null>(null);

readonly combobox = injectCombobox({
  props: () => ({
    options: users,
    modelValue: this.value(),
    optionLabel: (user) => user.name,
  }),
  onChange: (next) => this.value.set(next as User | null),
});

Structure

Each part of the markup receives a piece of the scope. Bind only the parts you render. Bind the attributes you need from combobox.snapshot(); Angular templates cannot spread a prop object.

Trigger + popup: a button opens a list below it. Most examples use this layout.

HeadlessCombobox (store)
└─ div #container                                   widget boundary (optional)
   ├─ button #trigger                               the trigger
   │  │      role, aria-controls, aria-expanded, aria-haspopup,
   │  │      aria-activedescendant from s.triggerProps
   │  │      (click)="s.triggerProps.onClick()"
   │  │      (keydown)="s.triggerProps.onKeydown($event)"
   │  └─ selected label
   ├─ div popup                                     the popup
   │  │      @if (s.isOpen) { ... }
   │  └─ ul
   │     │      id, role, aria-multiselectable from s.listboxProps
   │     └─ @for (option of s.filteredOptions; track option; let i = $index) {
   │        li
   │           id, role, aria-selected, aria-disabled, data-highlighted
   │           from s.getOptionProps(option, i)
   │           (click)="s.getOptionProps(option, i).onClick()"
   │           (mousedown)="s.getOptionProps(option, i).onMousedown($event)"
   │           (mousemove)="s.getOptionProps(option, i).onMousemove()"
   │           (focus)="s.getOptionProps(option, i).onFocus()"
   │           (keydown)="s.getOptionProps(option, i).onKeydown($event)"
   └─ input #input                                  search input (optional)
           id, role, aria-autocomplete, aria-controls,
           aria-activedescendant from s.inputProps
           (input)="s.inputProps.onInput($event)"
           (keydown)="s.inputProps.onKeydown($event)"

Typeahead: the text input itself is the combobox. Typing reopens the popup and filters.

HeadlessCombobox (store)
└─ div #container                                   widget boundary (optional)
   ├─ input #input                                  the combobox input
   │  │      role, aria-autocomplete, aria-controls, aria-expanded,
   │  │      aria-haspopup, aria-activedescendant from s.comboboxInputProps
   │  │      (click)="s.comboboxInputProps.onClick()"
   │  │      (focus)="s.comboboxInputProps.onFocus()"
   │  │      (input)="s.comboboxInputProps.onInput($event)"
   └─ div popup                                     the popup
      │      @if (s.isOpen) { ... }
      └─ ul
         │      id, role, aria-multiselectable from s.listboxProps
         └─ @for (option of s.filteredOptions; track option; let i = $index) {
            li
               id, role, aria-selected, aria-disabled, data-highlighted
               from s.getOptionProps(option, i)
               (click)="s.getOptionProps(option, i).onClick()"
               (mousedown)="s.getOptionProps(option, i).onMousedown($event)"
               (mousemove)="s.getOptionProps(option, i).onMousemove()"
               (focus)="s.getOptionProps(option, i).onFocus()"
               (keydown)="s.getOptionProps(option, i).onKeydown($event)"

Markup → scope

NameTypeDescription
wrapper elementsetContainerRefWidget boundary for click-outside and focus. Optional, recommended.
trigger buttontriggerProps, setTriggerRefrole="combobox". Toggles the popup and handles keyboard navigation.
typeahead inputcomboboxInputProps, setTriggerRef, setInputRefThe input is the combobox: typing reopens and filters.
search inputinputProps, setInputRefrole="searchbox". Filters while the popup stays open.
popup elementpopupStyle, setDropdownRefPositioning; add popover="manual" to use the native Popover API.
list elementlistboxProps, setListRefrole="listbox". The options container.
each option elementgetOptionProps(option, index), setOptionRef(option, el)Option semantics and select/highlight handlers.

Ref setters are optional. setOptionRef enables alignSelected and scroll-into-view; setContainerRef extends the click-outside boundary, for example to chips outside the field.

For CSS anchor positioning and the popover entry animation, see Styling.

Examples

The preview runs the Vue implementation. The code tab shows the same example for Angular.

The preview uses the native Popover API. Keyboard and hover share the same highlight, and the selected option is marked with a check.

Text options · single · no filter

A list of plain string options, single selection, no search input.

Framework (single, no filter)

Text options · single · internal state

An initial value seeds the internal selection; without a change handler the component keeps it internally.

Framework (single, no v-model)

Text options · single · select on tab

Press Tab with an option highlighted: it is selected and the popup closes (selectOnTab).

Framework (single, select on tab)

Object options · single · with filter

Object options with a searchable input.

Assign user (single, with filter)

Object options · single · separate value

Options carry a label and a value; the model holds the value only.

Framework id (single, separate value)

Text options · multiple · with filter

Multiple selection capped with max; selecting toggles, dropdown stays open.

Frameworks (multiple, max 3)

Text options · multiple · removable chips

Selected items as removable chips. The remove buttons live outside the combobox trigger, so the trigger stays a single focusable control.

Frameworks (multiple, max 3)
Vue Svelte

Text options · multiple · custom options

Each option renders its own checkbox for the selection state; the trigger shows the selected items as chips.

Frameworks (multiple, custom options)

Object options · multiple · validated

Multiple selection with required + min/max validation and a rendered message.

Reviewers (multiple, 2 to 4 required)

Select at least 2 options.

Select alignment

No search input; the dropdown aligns so the selected option overlays the trigger.

Assign user

Typeahead (editable combobox)

Canonical APG editable pattern: the text input itself is the combobox (role=combobox); type to filter.

Language (typeahead, editable)

Typeahead · chips inside the field

GitHub-style topic input: chips and the text input share one bordered field. The field is a plain container, so each chip can carry a remove button without nesting controls.

Topics (typeahead, removable chips in the field)
TypeScript

Composable · single · typeahead

The same behavior without the component. useHeadlessCombobox exposes the state, ARIA bags, and actions; wire the markup with plain refs.

Language (composable, typeahead)

Composable · programmatic control

open, close, select, and clear are plain functions, so the buttons outside the widget can call them. clickOutsideFilter keeps the popup open while the panel is used.

Drive it from anywhere:

Selected: none · popup closed

Member (composable, programmatic)

injectCombobox

injectCombobox is the Angular entry point. It creates the signal store and registers teardown through DestroyRef; createComboboxStore is the non-DI factory.

Pass props as an object or getter. modelValue stays inside props; onChange and injector are options on the helper.

snapshot() is a read-only signal. Read it in the template and call actions from it. Ref setters are on the snapshot.

import { Component, signal } from '@angular/core';
import { injectCombobox } from '@pdanpdan/headless-combobox-angular';

interface User {
  id: number;
  name: string;
}

const users: User[] = [
  { id: 1, name: 'Wade Cooper' },
  { id: 2, name: 'Arlene Mccoy' },
];

@Component({
  standalone: true,
  selector: 'app-example',
  template: `
    @let s = combobox.snapshot();

    <div #container>
      <input
        #input
        role="combobox"
        [attr.aria-expanded]="s.isOpen"
        [value]="s.searchQuery ?? value()?.name ?? ''"
        (input)="s.setSearchQuery($any($event.target).value)"
        (keydown)="s.handleKeydown($event)"
      />
      @if (s.isOpen) {
        <ul role="listbox">
          @for (user of s.filteredOptions; track user.id) {
            <li
              role="option"
              [attr.aria-selected]="s.isSelected(user)"
              (click)="s.select(user)"
            >
              {{ user.name }}
            </li>
          }
        </ul>
      }
    </div>
  `,
})
export class Example {
  readonly value = signal<User | null>(null);

  readonly combobox = injectCombobox<User, User>({
    props: () => ({
      modelValue: this.value(),
      options: users,
      optionLabel: (user) => user.name,
    }),
    onChange: (next) => this.value.set(next as User | null),
  });
}

The Composable · programmatic control example drives the store from buttons outside the widget.

API

Store options

The value and behavior fields go inside the props object passed to injectCombobox. onChange and injector are options on the helper itself.

NameTypeDefaultDescription
propsHeadlessComboboxProps<O, V, Q> | (() => HeadlessComboboxProps<O, V, Q>)n/aProps object or getter. The value is passed as props.modelValue.
onChange(value: V | V[] | null) => voidn/aCalled for every selection change.
injectorInjectorcurrent injectorUsed for afterNextRender ticking when creating the store outside DI.
optionsO[]n/aList of options.
multiplebooleanfalseEnable multiple selection.
minLengthnumbern/aMultiple: minimum number of selected options (validation).
maxLengthnumbern/aMultiple: maximum selected. Blocks adding beyond it.
requiredbooleanfalseRequire a selection (single: a value; multiple: at least one).
disabledbooleanfalseDisable the control: not focusable, cannot open or change.
readonlybooleanfalseRead-only: focusable, shows the value, but cannot open or change.
closeOnSelectboolean | null!multipleClose the dropdown after selecting.
closeOnClickOutsidebooleantrueClose when clicking outside the widget boundary.
clickOutsideFilter(target: EventTarget | null) => booleann/aReturn false to keep the dropdown open for an outside target.
selectOnTabbooleanfalseOn Tab, when focus leaves the widget: select the highlighted option and close.
optionValue(option: O) => Voption itselfMaps an option to the value stored in the model.
optionLabel(option: O) => stringString(option)Maps an option to a string for filtering and rendering.
optionFilter(option: O, query: Q) => booleansubstringCustom filter function. Q defaults to string.
idstringgeneratedBase id for accessibility attributes.
alignSelectedbooleanfalseAlign the dropdown so the selected option covers the trigger.
errorMessagesPartial<Record<HeadlessComboboxErrorCode, string>>n/aOverride default validation messages.

Scope

Read these values from combobox.snapshot(). The store exposes the same values as a signal.

State

Live values for the current selection and popup.

NameTypeDescription
isOpenbooleanWhether the dropdown is open.
multiplebooleanWhether multiple selection is enabled.
disabledbooleanWhether the control is disabled.
readonlybooleanWhether the control is read-only.
searchQueryQ | undefinedCurrent search query. Q defaults to string.
filteredOptionsT[]Options after applying the filter.
highlightedIndexnumberIndex of the highlighted option (-1 when none).
alignmentOffsetnumberPixel offset used for alignment.
cssAnchorNamestringUnique CSS anchor-name for popover positioning.
popupStyleHeadlessComboboxPopupStyleDefault popup positioning style. Spread or merge it onto the dropdown.
selectedCountnumberNumber of selected options.
selectedListV[]Selected values (single mode: a single-element array).
canSelectMorebooleanFalse when at maxLength (multiple).
isSelected(option: T) => booleanWhether an option is selected.
validbooleanWhether the current selection passes validation.
errorsHeadlessComboboxErrorCode[]Active validation errors ('required' | 'minlength' | 'maxlength').
validationMessagestringHuman-readable message for the first error.

ARIA prop bags

Bind the attributes you need from `combobox.snapshot()`; Angular templates cannot spread a prop object.

NameTypeDescription
triggerPropsHeadlessComboboxTriggerPropsrole=combobox, aria-expanded, aria-activedescendant, toggle and keydown handlers.
inputPropsHeadlessComboboxInputPropsSearch input attributes, aria-activedescendant, and keydown handling.
comboboxInputPropsHeadlessComboboxComboboxInputPropsTypeahead input attributes, open and focus handlers.
listboxPropsHeadlessComboboxListboxPropsrole=listbox and aria-multiselectable.
getOptionProps(option, index) => HeadlessComboboxOptionPropsrole=option, aria-selected, aria-disabled, and select and highlight handlers.

Actions

Methods that drive the combobox.

NameTypeDescription
toggle() => voidToggle the dropdown open or closed.
open() => voidOpen the dropdown.
close(returnFocus?: boolean) => voidClose the dropdown.
select(option: T) => voidSelect (single) or toggle (multiple) an option.
clear() => voidClear the selection (null or []).
setSearchQuery(value: Q | undefined) => voidUpdate the search query.
setHighlightedIndex(index: number) => voidSet the highlighted option. Wire it to hover to match keyboard behavior.
focusInput() => voidFocus the filter input while the popup stays open.
handleKeydown(event: KeyboardEvent) => voidKeyboard navigation handler.

Ref setters

Attach elements to the store. Bind only the elements your markup uses.

NameTypeDescription
setContainerRefref fnThe root container element.
setTriggerRefref fnThe trigger button or typeahead input.
setDropdownRefref fnThe dropdown popup element.
setInputRefref fnThe search input element.
setListRefref fnThe options list element.
setOptionRef(option, el) => voidEach option element. Needed for alignSelected and scroll-into-view.