# Cascade select

A form field picking one value from nested options, such as country, region and city. Each open option shows its children beside it; on a phone the panel steps through one level at a time.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-cascade-select`
- Source: [libs/ui/src/lib/organisms/cascade-select/cascade-select.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/organisms/cascade-select/cascade-select.ts)

```typescript title="Import"
import { CascadeSelect, CascadeSelectOptionTemplate } from '@vigdx/ui/cascade-select';
```

## Basic

Options are your own objects. `optionLabel` and `optionValue` are functions (by default the option's `label` and the option itself); `optionChildren` and `optionDisabled` read `children` and `disabled` unless you pass your own. Only options without children are chosen, which writes `optionValue(option)` to `[(value)]`; opening the panel shows the path to the value. Hover or click opens a level, and a diagonal move toward it keeps it open.

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

import { PLACES, placeCode, placeName } from './places';

@Component({
  selector: 'app-cascade-select-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CascadeSelect],
  template: `
    <div class="flex w-full max-w-xs flex-col gap-3">
      <vig-cascade-select
        label="City"
        placeholder="Choose a city"
        [options]="places"
        [optionLabel]="name"
        [optionValue]="code"
        [(value)]="city"
        clearable
      />
      <p class="text-sm text-muted-foreground">Value: {{ city() ?? 'none' }}</p>
    </div>
  `,
})
export class CascadeSelectBasicDemo {
  protected readonly places = PLACES;
  protected readonly name = placeName;
  protected readonly code = placeCode;
  protected readonly city = signal<string | null>('MUC');
}
```

## Choosing groups, path and option content

`selectableGroups` lets a region or a country be chosen too: a click on its label or Enter chooses it, its chevron or ArrowRight opens it. `display="path"` shows the whole path in the trigger, and a `vigCascadeSelectOption` template (typed by `vigCascadeSelectOptionOf`) renders the options.

```typescript title="cascade-select-groups.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { CascadeSelect, CascadeSelectOptionTemplate } from '@vigdx/ui/cascade-select';

import { PLACES, placeCode, placeName } from './places';

@Component({
  selector: 'app-cascade-select-groups',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CascadeSelect, CascadeSelectOptionTemplate],
  template: `
    <div class="flex w-full max-w-xs flex-col gap-3">
      <vig-cascade-select
        label="Delivery area"
        display="path"
        selectableGroups
        [options]="places"
        [optionLabel]="name"
        [optionValue]="code"
        [(value)]="area"
      >
        <ng-template vigCascadeSelectOption [vigCascadeSelectOptionOf]="places" let-place>
          <span class="min-w-0 flex-1 truncate">{{ place.name }}</span>
          <span class="font-mono text-xs text-muted-foreground">{{ place.code }}</span>
        </ng-template>
      </vig-cascade-select>
      <p class="text-sm text-muted-foreground">Value: {{ area() ?? 'none' }}</p>
    </div>
  `,
})
export class CascadeSelectGroupsDemo {
  protected readonly places = PLACES;
  protected readonly name = placeName;
  protected readonly code = placeCode;
  protected readonly area = signal<string | null>('TR-AE');
}
```

## Lazy levels

Options whose `optionChildren` returns `undefined` load through `loadChildren(option, signal)` the first time they open, and stay loaded. The signal aborts when the level closes first; a rejected promise shows a retry row, and an empty array makes the option a leaf (chosen at once when Enter or a click started the load). `valueLabel(value)` labels a value whose option is not loaded yet. Return `null` from `optionChildren` (or a `children: null` field) for options that never have children.

```typescript title="cascade-select-lazy.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { CascadeSelect, type CascadeSelectLoader } from '@vigdx/ui/cascade-select';

interface Category {
  readonly id: string;
  readonly title: string;
  /** `null`: a leaf. Left out: the loader fetches the children. */
  readonly children?: readonly Category[] | null;
}

@Component({
  selector: 'app-cascade-select-lazy',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [CascadeSelect],
  template: `
    <div class="flex w-full max-w-xs flex-col gap-3">
      <vig-cascade-select
        label="Category"
        placeholder="Browse categories"
        [options]="roots"
        [optionLabel]="title"
        [optionValue]="id"
        [loadChildren]="load"
        [(value)]="category"
      />
      <p class="text-sm text-muted-foreground">Value: {{ category() ?? 'none' }}</p>
    </div>
  `,
})
export class CascadeSelectLazyDemo {
  protected readonly roots: readonly Category[] = [
    { id: 'books', title: 'Books' },
    { id: 'music', title: 'Music' },
    { id: 'garden', title: 'Garden' },
  ];
  protected readonly title = (category: Category) => category.title;
  protected readonly id = (category: Category) => category.id;
  protected readonly category = signal<string | null>(null);

  // Stands in for `fetch(url, { signal })`: aborted when the level closes first.
  protected readonly load: CascadeSelectLoader<Category> = (parent, signal) =>
    new Promise((resolve, reject) => {
      const timer = setTimeout(
        () =>
          resolve(
            ['New', 'Popular', 'On sale'].map((title) => ({
              id: `${parent.id}/${title.toLowerCase().replace(' ', '-')}`,
              title: `${title} in ${parent.title}`,
              children: null,
            })),
          ),
        600,
      );
      signal.addEventListener('abort', () => {
        clearTimeout(timer);
        reject(signal.reason);
      });
    });
}
```

## Signal Forms

Bind a field with `[formField]`: errors, required, disabled and touched state come from the form. Clearing writes `null`, so type the field as nullable.

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

import { PLACES, placeCode, placeName } from './places';

@Component({
  selector: 'app-cascade-select-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, CascadeSelect],
  template: `
    <div class="max-w-xs">
      <vig-cascade-select
        label="Office"
        hint="Where you work most days."
        [options]="places"
        [optionLabel]="name"
        [optionValue]="code"
        [formField]="f.office"
      />
    </div>
  `,
})
export class CascadeSelectSignalFormsDemo {
  protected readonly places = PLACES;
  protected readonly name = placeName;
  protected readonly code = placeCode;
  private readonly model = signal<{ office: string | null }>({ office: null });
  protected readonly f = form(this.model, (path) => {
    required(path.office, { message: 'Choose an office.' });
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the field for `formControlName`, `formControl` and `ngModel`.

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

import { PLACES, placeCode, placeName } from './places';

@Component({
  selector: 'app-cascade-select-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, CascadeSelect, VigValueAccessor],
  template: `
    <form
      class="flex max-w-xs flex-col gap-4"
      [formGroup]="form"
      (ngSubmit)="form.markAllAsTouched()"
    >
      <vig-cascade-select
        label="Warehouse"
        formControlName="warehouse"
        [options]="places"
        [optionLabel]="name"
        [optionValue]="code"
      />
      <div class="flex gap-2">
        <vig-button type="submit" label="Save" />
        <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 CascadeSelectReactiveFormsDemo {
  protected readonly places = PLACES;
  protected readonly name = placeName;
  protected readonly code = placeCode;
  protected readonly form = new FormGroup({
    warehouse: new FormControl<string | null>(null, Validators.required),
  });
}
```

## 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="cascade-select"][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="cascade-select"]`

| Part | Element | data-state |
| --- | --- | --- |
| `field` | Positioned wrapper of the label, trigger and buttons. |   |
| `label` | The visible (or floating) label. |   |
| `trigger` | The `role="combobox"` button. | `open, closed` |
| `value` | The chosen option (or its path) and, for assistive tech, its ancestors. |   |
| `placeholder` | The placeholder text in the trigger. |   |
| `indicator` | The chevron. |   |
| `clear` | The clear button (`clearable`). |   |
| `panel` | The overlay panel of the top level, in the overlay container. |   |
| `header` | Narrow screens: the row above a deeper level. |   |
| `back` | Narrow screens: the button back to the previous level. |   |
| `heading` | Narrow screens: the label of the open option. |   |
| `listbox` | The `role="listbox"` of the level the panel shows, named by its option (the field at the top; `aria-busy` while it loads). |   |
| `level` | Wide screens: an open option's children, a `role="listbox"` named by it, in an overlay beside it. |   |
| `option` | A `role="option"` (`aria-selected`, `aria-disabled`; options with children are described as having options and are `aria-busy` while they load). | `open, closed` |
| `option-label` | The option text (without a custom template). |   |
| `check` | The check mark of the chosen option. |   |
| `group-indicator` | The chevron of an option with children. |   |
| `loading` | The busy ring of an option whose children load. |   |
| `level-status` | The loading row of a level that waits for its options. |   |
| `load-error` | The row of a level whose options failed to load. |   |
| `retry` | The retry text of that row. |   |
| `empty` | The row shown without options. |   |
| `status` | The visually hidden `role="status"` region announcing the level entered. |   |
| `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). |   |

| Attribute | Meaning |
| --- | --- |
| `data-opening` | On the overlay element (panel or `<dialog>`) while its entrance transition plays; removed once it settles (2s at most). Style the entrance with `data-opening:` utilities. |
| `data-closing` | On the overlay element while its exit transition plays, before it closes; removed once it settles (2s at most). Style the closed look with `data-closing:` utilities. |

## Accessibility

- The trigger is an APG `role="combobox"` labelled by the field label, with `aria-haspopup="listbox"`. Each level is a `role="listbox"` named by its option ("Türkiye"; the top level by the field). Focus stays on the trigger: its `aria-controls` names the listbox of the active level and `aria-activedescendant` the active option there; both are left out while the element they name is not on the page (a level still attaching or loading).
- Options with a level of their own are described as having options ("has options"), and entering a level is announced through a polite status ("Türkiye, 3 options").
- ArrowDown, ArrowUp, Enter or Space open the panel on the value's path. ArrowUp and ArrowDown move within a level, Home and End to its ends, ArrowRight opens the active option's level and moves into it, ArrowLeft goes back (mirrored in right-to-left pages), typing jumps to an option, Enter or Space chooses it, Escape closes the panel and Tab closes it and moves on.
- The value reads with its path, the option first: "Istanbul, Marmara, Türkiye". An option whose children load is `aria-busy` and described by the loading text; a failed load becomes a retry option in its level, and reopening the panel tries again. A value under a disabled option still shows, but the panel opens on the nearest enabled option.
- On narrow screens the Back button (and ArrowLeft) returns to the previous level; its targets, like the options, are at least 44px tall on touch screens.
- Texts are translated with the locale or per instance through `labels` (`ariaLabel`, `clearAriaLabel`, `backLabel`, `hasOptionsLabel`, `levelAnnouncement`, `loadingLabel`, `errorLabel`, `retryLabel`, `emptyLabel`).

## API

### CascadeSelect

Selector: `vig-cascade-select` · Kind: component

A form field picking one value from nested options, e.g. country → state → city: the panel shows a level per open option, side by side, and choosing an option without children sets the value. On narrow screens the panel shows one level at a time with a Back button.

Options are your own objects: `optionLabel`, `optionValue`, `optionChildren` and `optionDisabled` read them (by default their `label`, the option itself, `children` and `disabled`), and `loadChildren` fetches levels on demand. Values compare with `===`.

**Example :**

```html
<vig-cascade-select label="City" [options]="countries" [optionValue]="cityCode" [formField]="form.city" />
```

The trigger is a combobox (APG) whose popup is the listbox of the active level: focus stays on it and the arrow keys move the active option (`aria-activedescendant`), Right (Left in RTL) opens a level, Left goes back, Enter picks, typing jumps to an option. The chosen value is announced with its path ("Istanbul, Türkiye"). Works with Signal Forms and, through `VigValueAccessor`, with Reactive Forms and `ngModel`.

While it plays its entrance or exit transition, the animating element carries `data-opening` or `data-closing` (stable hooks for styling and for waiting in tests; see the theming guide). panel listbox level option option-label check group-indicator loading level-status load-error retry empty header back heading status cascade-select open closed data-opening data-closing

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `clearable` | `boolean` | `false` | Shows a button that clears the value while one is set. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `display` | `"label" \| "path"` | `'label'` | The trigger shows the chosen option's `label`, or its whole `path` ("Türkiye / Istanbul"). |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hideLabel` | `boolean` | `false` | Visually hides the label, which still names the field; pair it with a placeholder. |
| `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. |
| `labels` | `Partial<CascadeSelectLabels>` | — | Texts (i18n); locale defaults. |
| `loadChildren` | `CascadeSelectLoader<T> \| undefined` | `undefined` | Fetches the children of options without their own; see `CascadeSelectLoader`. |
| `name` | `string` | `''` | — |
| `optionChildren` | `CascadeSelectChildren<T>` | `defaultOptionChildren` | Children of an option: an array (empty or `null` for a leaf), or `undefined` for children `loadChildren` fetches. Its `children` by default. |
| `optionDisabled` | `(option: T) => boolean` | `defaultOptionDisabled` | Whether an option is disabled: dimmed, skipped by the keys, never opened or chosen. |
| `optionLabel` | `(option: T) => string` | `defaultOptionLabel` | Text of an option; its `label` (else the option as text) by default. |
| `options` | `readonly T[]` | `[]` | The top-level options. |
| `optionValue` | `(option: T) => V` | `identity` | What choosing an option writes to `value`; the option itself by default. Compared with `===`. |
| `pending` | `boolean` | `false` | — |
| `placeholder` | `string \| undefined` | `undefined` | Shown in the trigger while nothing is chosen. |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `selectableGroups` | `boolean` | `false` | Options with children can be chosen too (Enter or a click on the label); the chevron opens them. |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `V \| null` | `null` | The value of the chosen option (`optionValue`); `null` while none is. |
| `valueLabel` | `((value: V) => string \| undefined) \| undefined` | `undefined` | Labels a value whose option is not known: not loaded yet (under a lazy option) or gone from `options`. Without it, or when it returns `undefined`, the trigger shows the value as text (an object value with the default `optionValue` shows its `optionLabel`). |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `V \| null` | The value of the chosen option (`optionValue`); `null` while none is. |

#### 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` | Closes the panel without moving focus or marking the field touched; see `VigFormField.reset`. |

### CascadeSelectOptionTemplate

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

Custom content of the options of `vig-cascade-select` (in the panel; the trigger keeps the label text, and options keep `optionLabel` as their accessible name). Bind the same top-level options to `vigCascadeSelectOptionOf` to type `let-option`; without it the option is `unknown`.

**Example :**

```html
<ng-template vigCascadeSelectOption [vigCascadeSelectOptionOf]="places" let-place>
  <span aria-hidden="true">{{ place.flag }}</span> {{ place.name }}
</ng-template>
```

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `vigCascadeSelectOptionOf` | `readonly T[] \| null \| undefined` | `undefined` | Type-only: the options the template renders. Not read at runtime. |
