# Listbox

A list of options shown in the page rather than in a dropdown: one or many values, with an optional filter, checkboxes, groups and virtual scrolling for long lists. The value is always an array.

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

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

## Basic

Pass `options` as `ListboxOption` objects (`SelectOption` plus an optional `group`) and bind `[(value)]` to an array; empty is `[]`. Without `multiple` it holds at most one value, which follows the arrow keys like a native `<select size>`; the value stays an array either way, so a single-choice form field is typed `T[]`.

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

import { CITIES } from './options';

@Component({
  selector: 'app-listbox-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, Listbox],
  template: `
    <div class="max-w-xs">
      <vig-listbox label="City" [options]="cities" [(value)]="city" />
    </div>
    <p class="text-sm text-muted-foreground">Value: {{ city() | json }}</p>
  `,
})
export class ListboxBasicDemo {
  protected readonly cities = CITIES;
  protected readonly city = signal<string[]>(['lis']);
}
```

```typescript title="options.ts"
import type { ListboxOption } from '@vigdx/ui/listbox';

export const CITIES: ListboxOption[] = [
  { value: 'ist', label: 'İstanbul' },
  { value: 'ber', label: 'Berlin' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'osl', label: 'Oslo' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome', disabled: true },
  { value: 'vie', label: 'Vienna' },
];

export const TOPPINGS: ListboxOption[] = [
  { value: 'basil', label: 'Basil', group: 'Herbs' },
  { value: 'oregano', label: 'Oregano', group: 'Herbs' },
  { value: 'olives', label: 'Olives', group: 'Vegetables' },
  { value: 'peppers', label: 'Peppers', group: 'Vegetables' },
  { value: 'mushrooms', label: 'Mushrooms', group: 'Vegetables' },
  { value: 'mozzarella', label: 'Mozzarella', group: 'Cheese' },
  { value: 'gorgonzola', label: 'Gorgonzola', group: 'Cheese', disabled: true },
];
```

## Multiple, checkboxes, filter and groups

`multiple` keeps the values in selection order. `checkbox` adds a checkbox per option and a select-all row (only with `multiple`; a dev-mode warning says so otherwise), `filter` a search field that matches labels in the active locale. Consecutive options with the same `group` form a named group.

```typescript title="listbox-multiple.ts"
import { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Listbox } from '@vigdx/ui/listbox';

import { CITIES, TOPPINGS } from './options';

@Component({
  selector: 'app-listbox-multiple',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, Listbox],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-listbox label="Cities" multiple [options]="cities" [(value)]="pickedCities" />
      <vig-listbox
        label="Toppings"
        multiple
        checkbox
        filter
        [options]="toppings"
        [(value)]="pickedToppings"
      />
    </div>
    <p class="text-sm text-muted-foreground">
      Cities: {{ pickedCities() | json }} · Toppings: {{ pickedToppings() | json }}
    </p>
  `,
})
export class ListboxMultipleDemo {
  protected readonly cities = CITIES;
  protected readonly toppings = TOPPINGS;
  protected readonly pickedCities = signal<string[]>([]);
  protected readonly pickedToppings = signal<string[]>(['basil']);
}
```

```typescript title="options.ts"
import type { ListboxOption } from '@vigdx/ui/listbox';

export const CITIES: ListboxOption[] = [
  { value: 'ist', label: 'İstanbul' },
  { value: 'ber', label: 'Berlin' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'osl', label: 'Oslo' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome', disabled: true },
  { value: 'vie', label: 'Vienna' },
];

export const TOPPINGS: ListboxOption[] = [
  { value: 'basil', label: 'Basil', group: 'Herbs' },
  { value: 'oregano', label: 'Oregano', group: 'Herbs' },
  { value: 'olives', label: 'Olives', group: 'Vegetables' },
  { value: 'peppers', label: 'Peppers', group: 'Vegetables' },
  { value: 'mushrooms', label: 'Mushrooms', group: 'Vegetables' },
  { value: 'mozzarella', label: 'Mozzarella', group: 'Cheese' },
  { value: 'gorgonzola', label: 'Gorgonzola', group: 'Cheese', disabled: true },
];
```

## Long lists

From 500 options on (`virtualScroll` is `'auto'`) only the rows in view are rendered, with one row height; set `virtualScroll` to `true` or `false` to decide yourself. The height follows `--vig-listbox-max-height` (15rem), the virtual row height `--vig-listbox-row-height` (2.25em).

```typescript title="listbox-virtual.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Listbox, type ListboxOption } from '@vigdx/ui/listbox';

@Component({
  selector: 'app-listbox-virtual',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Listbox],
  template: `
    <div class="max-w-xs">
      <vig-listbox label="Invoices" multiple filter [options]="invoices" [(value)]="picked" />
    </div>
    <p class="text-sm text-muted-foreground">{{ picked().length }} of 10 000 selected</p>
  `,
})
export class ListboxVirtualDemo {
  // From 500 options on, only the rows in view are rendered.
  protected readonly invoices: ListboxOption<number>[] = Array.from({ length: 10_000 }, (_, i) => ({
    value: i + 1,
    label: `Invoice ${String(i + 1).padStart(5, '0')}`,
  }));
  protected readonly picked = signal<number[]>([]);
}
```

## Custom options and texts

A `vigSelectOption` template renders each option, as in `vig-select`; `labels` overrides the texts the list adds (`filterPlaceholder`, `filterAriaLabel`, `emptyLabel`, `noResultsLabel`, `selectAllLabel`).

```typescript title="listbox-template.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { Icon } from '@vigdx/ui/icon';
import { Listbox, type ListboxOption } from '@vigdx/ui/listbox';
import { SelectOptionTemplate } from '@vigdx/ui/select';

@Component({
  selector: 'app-listbox-template',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Icon, Listbox, SelectOptionTemplate],
  template: `
    <div class="max-w-xs">
      <vig-listbox
        label="Folder"
        size="lg"
        [options]="folders"
        [(value)]="folder"
        [labels]="{ emptyLabel: 'No folders yet' }"
      >
        <ng-template vigSelectOption [vigSelectOptionOf]="folders" let-option>
          <vig-icon [name]="option.icon ?? 'file'" />
          <span class="truncate">{{ option.label }}</span>
          <span class="ms-auto text-xs text-muted-foreground">{{ counts[option.value] }}</span>
        </ng-template>
      </vig-listbox>
    </div>
  `,
})
export class ListboxTemplateDemo {
  protected readonly folders: ListboxOption[] = [
    { value: 'inbox', label: 'Inbox', icon: 'inbox' },
    { value: 'drafts', label: 'Drafts' },
    { value: 'archive', label: 'Archive', icon: 'download' },
  ];
  protected readonly counts: Record<string, number> = { inbox: 12, drafts: 3, archive: 248 };
  protected readonly folder = signal<string[]>(['inbox']);
}
```

## Forms

`vig-listbox` implements `FormValueControl<T[]>` for Signal Forms; import `VigValueAccessor` for `formControl`, `formControlName` or `ngModel`. Signal Forms' `required()` treats `[]` as filled, so require a value with `minLength(path, 1)` or check the length with `validate()`. Values compare with `===` and must be unique (a dev-mode warning flags duplicates).

```typescript title="listbox-forms.ts"
import { JsonPipe } from '@angular/common';
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { FormField, form, validate } from '@angular/forms/signals';
import { VigValueAccessor } from '@vigdx/ui/core';
import { Listbox } from '@vigdx/ui/listbox';

import { CITIES } from './options';

@Component({
  selector: 'app-listbox-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, FormField, ReactiveFormsModule, Listbox, VigValueAccessor],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-listbox
        label="Signal Forms"
        hint="Pick two or more."
        multiple
        [options]="cities"
        [formField]="trip.cities"
      />
      <vig-listbox label="Reactive Forms" [options]="cities" [formControl]="home" />
    </div>
    <p class="text-sm text-muted-foreground">
      Valid: {{ trip().valid() ? 'yes' : 'no' }} · Home: {{ home.value | json }}
    </p>
  `,
})
export class ListboxFormsDemo {
  protected readonly cities = CITIES;
  protected readonly model = signal({ cities: ['ber'] as string[] });
  // required() treats [] as filled, so validate the length instead.
  protected readonly trip = form(this.model, (path) => {
    validate(path.cities, ({ value }) =>
      value().length < 2 ? { kind: 'minItems', message: 'Pick at least two cities.' } : undefined,
    );
  });
  // Validators.required treats an empty array as missing.
  protected readonly home = new FormControl<string[]>([], {
    nonNullable: true,
    validators: Validators.required,
  });
}
```

```typescript title="options.ts"
import type { ListboxOption } from '@vigdx/ui/listbox';

export const CITIES: ListboxOption[] = [
  { value: 'ist', label: 'İstanbul' },
  { value: 'ber', label: 'Berlin' },
  { value: 'lis', label: 'Lisbon' },
  { value: 'osl', label: 'Oslo' },
  { value: 'par', label: 'Paris' },
  { value: 'rom', label: 'Rome', disabled: true },
  { value: 'vie', label: 'Vienna' },
];

export const TOPPINGS: ListboxOption[] = [
  { value: 'basil', label: 'Basil', group: 'Herbs' },
  { value: 'oregano', label: 'Oregano', group: 'Herbs' },
  { value: 'olives', label: 'Olives', group: 'Vegetables' },
  { value: 'peppers', label: 'Peppers', group: 'Vegetables' },
  { value: 'mushrooms', label: 'Mushrooms', group: 'Vegetables' },
  { value: 'mozzarella', label: 'Mozzarella', group: 'Cheese' },
  { value: 'gorgonzola', label: 'Gorgonzola', group: 'Cheese', disabled: true },
];
```

## Listbox or select

A listbox keeps every option on screen, which suits a handful of choices that people compare or a long list they scan with a filter. When space is short, use a [select](https://vigdx.com/components/select.md) or a [multi select](https://vigdx.com/components/multi-select.md): the same options and value in a dropdown. To order a list, or to move items between two lists, use an [order list](https://vigdx.com/components/order-list.md) or a [pick list](https://vigdx.com/components/pick-list.md), which build on the listbox.

## 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="listbox"][data-part="label"] { … }`: 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="listbox"]`

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible (or visually hidden) label naming the list. |   |
| `control` | The bordered box around the filter, select-all row, list and status. |   |
| `filter` | The search field above the list (`filter`). |   |
| `select-all` | The select-all toggle (`checkbox` with `multiple`; `aria-pressed`). |   |
| `listbox` | The focusable `role="listbox"`; a `cdk-virtual-scroll-viewport` while virtualized. |   |
| `group` | A `role="group"` of options sharing a `group` heading. |   |
| `group-heading` | The heading of a group (a hidden-from-AT row while virtualized). |   |
| `option` | One option (`aria-selected`, `aria-disabled`). | `selected` |
| `checkbox` | The checkbox of an option (`checkbox`). |   |
| `check` | The check mark of a selected option (without `checkbox`). |   |
| `status` | The polite `role="status"` region under the list. |   |
| `empty` | The "no options" or "no results" message in the status. |   |
| `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). |   |

## Accessibility

- Follows the WAI-ARIA APG listbox pattern: a `role="listbox"` named by the label, with `aria-multiselectable` in `multiple` mode, and options reporting `aria-selected` and `aria-disabled`.
- Focus stays on the list and points at the active option through `aria-activedescendant`, so it keeps working while the list is virtualized; the active option draws an outline that forced-colors mode keeps, and selection shows a check mark or checkbox, never a tint alone. While virtualized, options carry `aria-setsize` and `aria-posinset`, the reference is set only while the active option is rendered, and the group name describes each option.
- ArrowUp and ArrowDown move, Home and End jump, PageUp and PageDown move a page, typing jumps to a matching label. In single mode the selection follows; in `multiple` mode Space toggles, Shift+arrows toggle the next option, Shift+Space and Shift+click select a range, Ctrl+Shift+Home/End select to the ends and Ctrl/Cmd+A selects every option (again to clear).
- The filter is a search field controlling the list; ArrowDown moves on into the list. When nothing matches, a status message says so.
- Hint and error are linked through `aria-describedby`; an invalid list sets `aria-invalid`, a read-only one `aria-readonly` (it can still be browsed), a disabled one (`aria-disabled`) stays focusable, so a long list can still be scrolled and read, but nothing can be selected.

## API

### Listbox

Selector: `vig-listbox` · Kind: component

A list of options shown in the page (APG listbox): one or many values, an optional filter, checkboxes, groups and virtual scrolling for long lists. Focus stays on the list and the active option is exposed through `aria-activedescendant`, so it keeps working while virtualized. The value is always an array in selection order (`[]` when empty); single selection holds at most one value and follows the arrow keys, like a native `<select size>`.

**Example :**

```html
<vig-listbox label="Cities" [options]="cities" [(value)]="picked" multiple filter />
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `checkbox` | `boolean` | `false` | With `multiple`, a checkbox per option and a select-all row; ignored (with a dev-mode warning) without it. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `filter` | `boolean` | `false` | A search field above the list that narrows the options by label (locale-aware). |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label; it still names the list for assistive tech. |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | Visible label naming the list; also with `hideLabel`. |
| `labels` | `Partial<ListboxLabels>` | — | Texts (i18n) over the locale defaults. |
| `multiple` | `boolean` | `false` | Allows any number of values: Space toggles, Shift extends, Ctrl/Cmd+A selects all. Without it the value still is an array, of at most one value; a Signal Forms `required()` does not see `[]` as empty, so check it with `minLength(path, 1)`. |
| `name` | `string` | `''` | — |
| `options` | `readonly ListboxOption<T>[]` | `[]` | The options; values compare with `===`, so each must be unique. |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `size` | `FieldSize` | `'md'` | Text size and option padding. |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `T[]` | `[]` | The selected values in selection order; at most one without `multiple`. |
| `virtualScroll` | `ListboxVirtualScroll` | `'auto'` | Renders only the options in view; `'auto'` from `LISTBOX_VIRTUAL_THRESHOLD` options (and back below 400). A virtualized list cannot be dragged. |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `T[]` | The selected values in selection order; at most one without `multiple`. |

#### 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 the filter text as well; 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` | — |
