跳到正文
本页尚未翻译成中文,以下为英文原文。 查看英文版

Autocomplete ​

Overview ​

An accessible input field that filters and suggests options as users type, helping them find and select values from a list.

Example source: app.ts · app.html · app.css

Usage ​

Autocomplete works best when users need to select from a large set of options where typing is faster than scrolling. Consider using autocomplete when:

  • The option list is long (more than 20 items) - Typing narrows down choices faster than scrolling through a dropdown
  • Users know what they're looking for - They can type part of the expected value (like a state name, product, or username)
  • Options follow predictable patterns - Users can guess partial matches (like country codes, email domains, or categories)
  • Speed matters - Forms benefit from quick selection without extensive navigation

Avoid autocomplete when:

  • The list has fewer than 10 options - A regular dropdown or radio group provides better visibility
  • Users need to browse options - If discovery is important, show all options upfront
  • Options are unfamiliar - Users can't type what they don't know exists in the list

Features ​

Angular's autocomplete provides a fully accessible combobox implementation with:

  • Keyboard Navigation - Navigate options with arrow keys, select with Enter, close with Escape
  • Screen Reader Support - Built-in ARIA attributes for assistive technologies
  • Dynamic Highlight Behavior - Built-in support for inline selection suggestions
  • Signal-Based Reactivity - Reactive state management using Angular signals
  • Popover API Integration - Leverages the native HTML Popover API for optimal positioning
  • Bidirectional Text Support - Automatically handles right-to-left (RTL) languages

Examples ​

Auto-select mode ​

Users typing partial text expect immediate confirmation that their input matches an available option. Auto-select mode updates the input value to match the first filtered option as users type, reducing the number of keystrokes needed and providing instant feedback that their search is on the right track.

Example source: app.ts · app.html · app.css

Manual selection mode ​

Manual selection mode keeps the typed text unchanged while users navigate the suggestion list, preventing confusion from automatic updates. The input only changes when users explicitly confirm their choice with Enter or a click.

Example source: app.ts · app.html · app.css

Highlight mode ​

Highlight mode allows the user to navigate options with arrow keys without changing the input value as they browse until they explicitly select a new option with Enter or click.

Example source: app.ts · app.html · app.css

Signal Forms Integration ​

Angular Aria integrates seamlessly with the signal-based Signal Forms API. You can encapsulate complex inputs into reusable custom control components implementing FormValueControl.

The following example demonstrates a country selector component implementing FormValueControl<string>, bound to the parent form using [formField] and protected by schema validation rules.

Example source: app.ts · app.html · country-selector.ts · country-selector.html · country-selector.css · app.css

Testing ​

The autocomplete pattern can be tested using a combination of ComboboxHarness and ListboxHarness from @angular/aria/combobox/testing and @angular/aria/listbox/testing. Here is an example of how to use the harnesses to test an autocomplete component:

ts
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {ComboboxHarness} from '@angular/aria/combobox/testing';
import {ListboxHarness} from '@angular/aria/listbox/testing';
import {MyAutocompleteComponent} from './my-autocomplete'; // Your component

describe('MyAutocompleteComponent', () => {
  let fixture: ComponentFixture<MyAutocompleteComponent>;
  let loader: HarnessLoader;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      imports: [MyAutocompleteComponent],
    });

    fixture = TestBed.createComponent(MyAutocompleteComponent);
    await fixture.whenStable();
    loader = TestbedHarnessEnvironment.loader(fixture);
  });

  it('should filter options based on input', async () => {
    const combobox = await loader.getHarness(ComboboxHarness);

    // Type in the input to trigger filtering
    await combobox.setValue('ap');
    expect(await combobox.isOpen()).toBe(true);

    // Get the listbox harness from the popup
    const listbox = await combobox.getPopupWidget(ListboxHarness);
    const options = await listbox.getOptions();

    // Verify options are filtered (e.g., 'Apple', 'Apricot')
    expect(options.length).toBe(2);
    expect(await options[0].getText()).toBe('Apple');

    // Select the first option
    await options[0].click();

    // Verify the input value is updated and popup is closed
    expect(await combobox.isOpen()).toBe(false);
    expect(await combobox.getValue()).toBe('Apple');
  });
});

API reference ​

For detailed API documentation, inspect the following API references:

基于 MIT 许可证发布。