# Autocomplete

A text field that suggests matching options while the user types. Use it for long lists people search by name, filtered in the browser or fetched from a server.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-autocomplete`, `ng-template[vigSelectOption]`
- Source: [libs/ui/src/lib/molecules/autocomplete/autocomplete.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/molecules/autocomplete/autocomplete.ts)

```typescript title="Import"
import { Autocomplete } from '@vigdx/ui/autocomplete';
import { SelectOptionTemplate } from '@vigdx/ui/select';
```

## Basic

Pass `options` and bind `[(value)]`; the list narrows to labels containing the typed text. `minQueryLength` sets how many characters open the list (`0` opens it on focus) and `clearable` adds a clear button. Text that matches no option reverts on blur.

```typescript title="autocomplete-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Autocomplete } from '@vigdx/ui/autocomplete';

import { CITIES } from './cities';

@Component({
  selector: 'app-autocomplete-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Autocomplete],
  template: `
    <div class="grid gap-4 sm:grid-cols-2">
      <vig-autocomplete
        label="Destination"
        placeholder="Type a city"
        [options]="cities"
        [(value)]="destination"
      />
      <vig-autocomplete
        label="Origin"
        hint="Suggestions open on focus."
        [options]="cities"
        [minQueryLength]="0"
        [clearable]="true"
        [(value)]="origin"
      />
    </div>
    <p class="text-sm text-muted-foreground">
      Destination: {{ destination() ?? 'none' }} · Origin: {{ origin() ?? 'none' }}
    </p>
  `,
})
export class AutocompleteBasicDemo {
  protected readonly cities = CITIES;
  protected readonly destination = signal<string | null>(null);
  protected readonly origin = signal<string | null>('ist');
}
```

```typescript title="cities.ts"
import type { SelectOption } from '@vigdx/ui/select';

export const CITIES: SelectOption[] = [
  { value: 'ams', label: 'Amsterdam' },
  { value: 'ank', label: 'Ankara' },
  { value: 'ath', label: 'Athens' },
  { value: 'ber', label: 'Berlin' },
  { value: 'bud', label: 'Budapest' },
  { value: 'ist', label: 'Istanbul' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'lon', label: 'London' },
  { value: 'mad', label: 'Madrid' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome' },
  { value: 'vie', label: 'Vienna' },
  { value: 'kyiv', label: 'Kyiv', disabled: true },
];
```

## Server search

With `[localFilter]="false"` the field shows `options` as given. Listen to `searchRequest`, which fires once typing pauses for `debounce` ms, load results into `options` and set `loading` meanwhile to show a spinner. `queryChange` is the undebounced counterpart: it emits the text on every keystroke, e.g. for a character counter; use `searchRequest` for requests.

```typescript title="autocomplete-server.ts"
import { ChangeDetectionStrategy, Component, DestroyRef, inject, signal } from '@angular/core';
import { Autocomplete } from '@vigdx/ui/autocomplete';
import { type SelectOption } from '@vigdx/ui/select';

import { CITIES } from './cities';

@Component({
  selector: 'app-autocomplete-server',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Autocomplete],
  template: `
    <div class="max-w-sm">
      <vig-autocomplete
        label="City"
        hint="Results come from a (simulated) server."
        [options]="results()"
        [localFilter]="false"
        [loading]="loading()"
        [debounce]="300"
        [clearable]="true"
        (searchRequest)="search($event)"
        [(value)]="city"
      />
    </div>
    <p class="text-sm text-muted-foreground">Value: {{ city() ?? 'none' }}</p>
  `,
})
export class AutocompleteServerDemo {
  protected readonly results = signal<SelectOption[]>([]);
  protected readonly loading = signal(false);
  protected readonly city = signal<string | null>(null);
  private timer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  // Stands in for an HTTP call; searchRequest fires once typing pauses.
  protected search(query: string): void {
    this.loading.set(true);
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      const q = query.toLocaleLowerCase();
      this.results.set(CITIES.filter((c) => c.label.toLocaleLowerCase().includes(q)));
      this.loading.set(false);
    }, 600);
  }
}
```

```typescript title="cities.ts"
import type { SelectOption } from '@vigdx/ui/select';

export const CITIES: SelectOption[] = [
  { value: 'ams', label: 'Amsterdam' },
  { value: 'ank', label: 'Ankara' },
  { value: 'ath', label: 'Athens' },
  { value: 'ber', label: 'Berlin' },
  { value: 'bud', label: 'Budapest' },
  { value: 'ist', label: 'Istanbul' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'lon', label: 'London' },
  { value: 'mad', label: 'Madrid' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome' },
  { value: 'vie', label: 'Vienna' },
  { value: 'kyiv', label: 'Kyiv', disabled: true },
];
```

## Object values

Values can be objects. They are compared by reference, so the bound value must be one of the option instances. `displayWith` sets the text shown in the field for the selected value.

```typescript title="autocomplete-objects.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Autocomplete } from '@vigdx/ui/autocomplete';
import { type SelectOption } from '@vigdx/ui/select';

interface Person {
  id: number;
  name: string;
  email: string;
}

const PEOPLE: Person[] = [
  { id: 1, name: 'Ada Lovelace', email: 'ada@example.com' },
  { id: 2, name: 'Grace Hopper', email: 'grace@example.com' },
  { id: 3, name: 'Alan Turing', email: 'alan@example.com' },
  { id: 4, name: 'Katherine Johnson', email: 'katherine@example.com' },
];

@Component({
  selector: 'app-autocomplete-objects',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Autocomplete],
  template: `
    <div class="max-w-sm">
      <vig-autocomplete
        label="Assignee"
        [options]="people"
        [displayWith]="displayPerson"
        [clearable]="true"
        [(value)]="assignee"
      />
    </div>
    <p class="text-sm text-muted-foreground">Assignee: {{ assignee()?.email ?? 'nobody' }}</p>
  `,
})
export class AutocompleteObjectsDemo {
  // Object values are compared by reference: reuse the same instances.
  protected readonly people: SelectOption<Person>[] = PEOPLE.map((person) => ({
    value: person,
    label: `${person.name} (${person.email})`,
  }));
  protected readonly assignee = signal<Person | null>(PEOPLE[1]);
  protected readonly displayPerson = (person: Person) => person.name;
}
```

## Free text

`allowCustom` keeps typed text that matches no option as the value, so suggestions are optional. Use it with string values.

```typescript title="autocomplete-allow-custom.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Autocomplete } from '@vigdx/ui/autocomplete';
import { type SelectOption } from '@vigdx/ui/select';

@Component({
  selector: 'app-autocomplete-allow-custom',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Autocomplete],
  template: `
    <div class="max-w-sm">
      <vig-autocomplete
        label="Job title"
        hint="Pick a suggestion or keep your own text."
        [options]="titles"
        [allowCustom]="true"
        [(value)]="title"
      />
    </div>
    <p class="text-sm text-muted-foreground">Value: {{ title() ?? 'none' }}</p>
  `,
})
export class AutocompleteAllowCustomDemo {
  protected readonly titles: SelectOption[] = [
    'Designer',
    'Developer',
    'Engineering manager',
    'Product manager',
    'QA engineer',
  ].map((title) => ({ value: title, label: title }));
  protected readonly title = signal<string | null>(null);
}
```

## Label, error, states and sizes

`labelPosition="top"` puts the label above the field and `emptyMessage` replaces the "no results" text. Errors show once the field is `touched` and `invalid`. `size` is `sm`, `md` (default) or `lg`.

```typescript title="autocomplete-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Autocomplete } from '@vigdx/ui/autocomplete';

import { CITIES } from './cities';

@Component({
  selector: 'app-autocomplete-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Autocomplete],
  template: `
    <div class="grid gap-4 sm:grid-cols-2">
      <vig-autocomplete
        label="City"
        labelPosition="top"
        placeholder="Type a city"
        emptyMessage="No city matches."
        [options]="cities"
      />
      <vig-autocomplete
        label="City"
        labelPosition="top"
        placeholder="Type a city"
        [options]="cities"
        [required]="true"
        [touched]="true"
        [invalid]="true"
        [errors]="[{ kind: 'required' }]"
        [errorMessages]="{ required: 'Choose a city.' }"
      />
      <vig-autocomplete label="Disabled" value="par" [options]="cities" [disabled]="true" />
      <vig-autocomplete label="Read-only" value="rom" [options]="cities" [readonly]="true" />
    </div>
    <div class="grid gap-4 sm:grid-cols-3">
      <vig-autocomplete label="Small" size="sm" value="ber" [options]="cities" />
      <vig-autocomplete label="Medium" size="md" value="ber" [options]="cities" />
      <vig-autocomplete label="Large" size="lg" value="ber" [options]="cities" />
    </div>
  `,
})
export class AutocompleteStatesDemo {
  protected readonly cities = CITIES;
}
```

```typescript title="cities.ts"
import type { SelectOption } from '@vigdx/ui/select';

export const CITIES: SelectOption[] = [
  { value: 'ams', label: 'Amsterdam' },
  { value: 'ank', label: 'Ankara' },
  { value: 'ath', label: 'Athens' },
  { value: 'ber', label: 'Berlin' },
  { value: 'bud', label: 'Budapest' },
  { value: 'ist', label: 'Istanbul' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'lon', label: 'London' },
  { value: 'mad', label: 'Madrid' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome' },
  { value: 'vie', label: 'Vienna' },
  { value: 'kyiv', label: 'Kyiv', disabled: true },
];
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`.

```typescript title="autocomplete-reactive-forms.ts"
import { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Autocomplete } from '@vigdx/ui/autocomplete';
import { Button } from '@vigdx/ui/button';
import { VigValueAccessor } from '@vigdx/ui/core';

import { CITIES } from './cities';

@Component({
  selector: 'app-autocomplete-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Autocomplete, Button, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" [formGroup]="form" (ngSubmit)="submit()">
      <div class="grid gap-4 sm:grid-cols-2">
        <vig-autocomplete label="From" formControlName="from" [options]="cities" />
        <vig-autocomplete label="To" formControlName="to" [options]="cities" />
      </div>
      <div class="flex gap-2">
        <vig-button type="submit" label="Search trips" />
        <vig-button label="Reset" variant="secondary" (click)="form.reset()" />
      </div>
      <pre class="rounded-input bg-subtle p-3 font-mono text-xs">{{ form.value | json }}</pre>
    </form>
  `,
})
export class AutocompleteReactiveFormsDemo {
  protected readonly cities = CITIES;
  protected readonly form = new FormGroup({
    from: new FormControl<string | null>('ams', Validators.required),
    to: new FormControl<string | null>(null, Validators.required),
  });

  protected submit(): void {
    this.form.markAllAsTouched();
  }
}
```

```typescript title="cities.ts"
import type { SelectOption } from '@vigdx/ui/select';

export const CITIES: SelectOption[] = [
  { value: 'ams', label: 'Amsterdam' },
  { value: 'ank', label: 'Ankara' },
  { value: 'ath', label: 'Athens' },
  { value: 'ber', label: 'Berlin' },
  { value: 'bud', label: 'Budapest' },
  { value: 'ist', label: 'Istanbul' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'lon', label: 'London' },
  { value: 'mad', label: 'Madrid' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome' },
  { value: 'vie', label: 'Vienna' },
  { value: 'kyiv', label: 'Kyiv', disabled: true },
];
```

## Signal Forms

`vig-autocomplete` implements `FormValueControl<T | null>`. Its query length input is called `minQueryLength` so that it does not clash with the `minLength` rule of Signal Forms.

```typescript title="autocomplete-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, form, required } from '@angular/forms/signals';
import { Autocomplete } from '@vigdx/ui/autocomplete';

import { CITIES } from './cities';

@Component({
  selector: 'app-autocomplete-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, Autocomplete],
  template: `
    <div class="max-w-sm">
      <vig-autocomplete label="Office" [options]="cities" [formField]="profile.office" />
    </div>
    <p class="text-sm text-muted-foreground">
      Valid: {{ profile().valid() ? 'yes' : 'no' }} · Office: {{ model().office ?? 'none' }}
    </p>
  `,
})
export class AutocompleteSignalFormsDemo {
  protected readonly cities = CITIES;
  protected readonly model = signal<{ office: string | null }>({ office: null });
  protected readonly profile = form(this.model, (path) => {
    required(path.office);
  });
}
```

```typescript title="cities.ts"
import type { SelectOption } from '@vigdx/ui/select';

export const CITIES: SelectOption[] = [
  { value: 'ams', label: 'Amsterdam' },
  { value: 'ank', label: 'Ankara' },
  { value: 'ath', label: 'Athens' },
  { value: 'ber', label: 'Berlin' },
  { value: 'bud', label: 'Budapest' },
  { value: 'ist', label: 'Istanbul' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'lon', label: 'London' },
  { value: 'mad', label: 'Madrid' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome' },
  { value: 'vie', label: 'Vienna' },
  { value: 'kyiv', label: 'Kyiv', disabled: true },
];
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="autocomplete"][data-part="field"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="autocomplete"]`

| Part | Element | data-state |
| --- | --- | --- |
| `field` | Positioned wrapper of the label and the control. |   |
| `label` | The visible (or floating) label. |   |
| `input` | The native `<input>`. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |
| `spinner` | The busy ring in the field while `loading`. |   |
| `clear` | The clear button (`clearable`). |   |
| `panel` | The overlay panel, rendered in the overlay container. |   |
| `listbox` | The `role="listbox"` list inside the panel. |   |
| `option` | One option (`aria-selected`, `aria-disabled`). |   |
| `empty` | The "no results" row. |   |
| `loading` | The loading row at the top of the panel. |   |
| `check` | The check mark of the selected option. |   |

## Accessibility

- Follows the APG combobox-with-list-autocomplete pattern: the input has `role="combobox"`, `aria-autocomplete="list"`, `aria-expanded` and `aria-controls` pointing at a `role="listbox"`.
- Focus stays in the input. ArrowDown and ArrowUp move through the suggestions (exposed with `aria-activedescendant`), Enter picks one, Escape closes the list.
- While `loading` the input sets `aria-busy` and the list shows a `role="status"` message (`loadingLabel`), so the wait is announced.
- The input is named by a real `<label for>`; hint and error are linked through `aria-describedby`. `clearAriaLabel`, `emptyMessage` and `loadingLabel` translate the added texts.

## API

### Autocomplete

Selector: `vig-autocomplete` · Kind: component

Text field with a suggestion list (APG combobox with list autocomplete). Suggestions come from `options`, filtered locally by label, or from the server: listen to `searchRequest` (debounced), set `localFilter` to false, and feed the results back through `options` while `loading` shows a spinner. Focus stays in the input; the active option is exposed through `aria-activedescendant`. Empty is null.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowCustom` | `boolean` | `false` | Keeps typed text that matches no option as the value (string models). |
| `clearable` | `boolean` | `false` | — |
| `clearAriaLabel` | `string \| undefined` | `undefined` | — |
| `debounce` | `number` | `250` | Delay before `searchRequest` fires, in milliseconds. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `displayWith` | `((value: T) => string) \| undefined` | `undefined` | Text shown in the field for a value; defaults to the option label. |
| `emptyMessage` | `string \| undefined` | `undefined` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label; it still names the control for assistive tech. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `labelPosition` | `LabelPosition` | `'float'` | `float` (default) rests the label inside the field; `top` sets it above a shorter field, for forms laid out with labels over their controls. |
| `loading` | `boolean` | `false` | Shows a spinner while server suggestions are on their way. |
| `loadingLabel` | `string \| undefined` | `undefined` | — |
| `localFilter` | `boolean` | `true` | Narrows `options` by the typed text. Turn off when `searchRequest` feeds server results. |
| `minQueryLength` | `number` | `1` | Characters needed before suggestions open (0 opens on focus). Not named `minLength`: that input belongs to the Signal Forms text-length contract. |
| `name` | `string` | `''` | — |
| `options` | `readonly SelectOption<T>[]` | `[]` | — |
| `pending` | `boolean` | `false` | — |
| `placeholder` | `string \| undefined` | `undefined` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `T \| null` | `null` | — |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `queryChange` | `string` | The typed text, on every keystroke. |
| `searchRequest` | `string` | The typed text once typing pauses for `debounce` ms and `minQueryLength` is met. |
| `touch` | `void` | — |
| `valueChange` | `T \| null` | — |

#### Methods

| Signature | Description |
| --- | --- |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `reset(): void` | Drops typed text and closes the suggestions; see `VigFormField.reset`. |

### SelectOptionTemplate

Selector: `ng-template[vigSelectOption]` · Kind: directive

Custom rendering for options of `vig-select`, `vig-multi-select`, `vig-listbox` and `vig-select-button`, replacing the default icon + label. `vig-select` also uses it for the selected value shown in the trigger.

Bind the same options to `vigSelectOptionOf` (like `ngForOf`) to type `let-option` in the template; without it the option value is `unknown`.

**Example :**

```html
<vig-select label="Status" [options]="statuses">
  <ng-template vigSelectOption [vigSelectOptionOf]="statuses" let-option>
    <i [class]="option.value" aria-hidden="true"></i> {{ option.label }}
  </ng-template>
</vig-select>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigSelectOptionOf` | `readonly SelectOption<T>[] \| null \| undefined` | `undefined` | Type-only: the options the template renders, so the template type checker infers the option value type. Not read at runtime. |

### VigValueAccessor

Kind: directive

Bridges the vigdx form fields to Reactive Forms (`formControl`, `formControlName`) and template-driven forms (`ngModel`). Import it next to the component; Signal Forms (`[formField]`) need no accessor.

#### Methods

| Signature | Description |
| --- | --- |
| `registerOnChange(fn: (value: unknown) => void): void` | — |
| `registerOnTouched(fn: () => void): void` | — |
| `setDisabledState(disabled: boolean): void` | — |
| `writeValue(value: unknown): void` | — |
