# Tree select

A form field whose panel holds a tree: pick a category, a region or a folder from a hierarchy. Its value is an array of node keys in every mode, so changing between one and several values never changes its type.

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

```typescript title="Import"
import { TreeSelect } from '@vigdx/ui/tree-select';
```

## Basic

Pass the same `TreeNode` objects as `vig-tree` takes. In `single` mode (the default) a click or Enter picks a node and closes the panel; `[(value)]` holds `[key]`, or `[]` when cleared. Opening the panel reveals the selected node.

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

import { REGIONS } from './regions';

@Component({
  selector: 'app-tree-select-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, TreeSelect],
  template: `
    <div class="flex w-full max-w-xs flex-col gap-3">
      <vig-tree-select label="Ships to" [nodes]="regions" [(value)]="region" clearable />
      <p class="text-sm text-muted-foreground">Value: {{ region() | json }}</p>
    </div>
  `,
})
export class TreeSelectBasicDemo {
  protected readonly regions = REGIONS;
  protected readonly region = signal<readonly string[]>(['de']);
}
```

## Several values

`multiple` toggles nodes and `checkbox` checks whole branches (tri-state, with `cascade`); the panel stays open. The trigger shows the labels comma-separated or as removable chips (`display="chip"`), a fully checked branch as its top node, and `selectedItemsLabel` above `maxSelectedLabels`. `filter` adds a search field; typing on the closed field starts the search, and `virtual` keeps large trees fast. Disabled values keep their state: their chips have no remove button and clearing leaves them. A key whose node is not loaded (yet) shows `keyLabel(key)`, else the key itself; such keys stay when an ancestor is unchecked, since the field cannot tell they lie below it.

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

import { REGIONS } from './regions';

@Component({
  selector: 'app-tree-select-multiple',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [TreeSelect],
  template: `
    <div class="grid w-full gap-4 sm:grid-cols-2">
      <vig-tree-select
        label="Markets"
        selectionMode="checkbox"
        display="chip"
        [nodes]="regions"
        [(value)]="markets"
        filter
        clearable
      />
      <vig-tree-select
        label="Offices"
        selectionMode="multiple"
        [nodes]="regions"
        [(value)]="offices"
        [maxSelectedLabels]="2"
      />
    </div>
  `,
})
export class TreeSelectMultipleDemo {
  protected readonly regions = REGIONS;
  protected readonly markets = signal<readonly string[]>(['asia', 'jp', 'kr', 'sg']);
  protected readonly offices = signal<readonly string[]>(['tr', 'de', 'us']);
}
```

## Signal Forms

Bind a field with `[formField]`: errors, required, disabled and touched state come from the form. An array field expresses “at least one” with `minLength`.

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

import { REGIONS } from './regions';

@Component({
  selector: 'app-tree-select-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, TreeSelect],
  template: `
    <div class="max-w-xs">
      <vig-tree-select
        label="Regions"
        hint="Pick at least one."
        selectionMode="multiple"
        display="chip"
        [nodes]="regions"
        [formField]="f.regions"
      />
    </div>
  `,
})
export class TreeSelectSignalFormsDemo {
  protected readonly regions = REGIONS;
  private readonly model = signal<{ regions: readonly string[] }>({ regions: [] });
  // `required()` never treats [] as empty: arrays express "at least one" with minLength.
  protected readonly f = form(this.model, (path) => {
    minLength(path.regions, 1, { message: 'Pick at least one region.' });
  });
}
```

## Reactive Forms

Import `VigValueAccessor` next to the field for `formControlName`, `formControl` and `ngModel`. A reset writes `[]`.

```typescript title="tree-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 { VigValueAccessor } from '@vigdx/ui/core';
import { TreeSelect } from '@vigdx/ui/tree-select';

import { REGIONS } from './regions';

@Component({
  selector: 'app-tree-select-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, TreeSelect, VigValueAccessor],
  template: `
    <form
      class="flex max-w-xs flex-col gap-4"
      [formGroup]="form"
      (ngSubmit)="form.markAllAsTouched()"
    >
      <vig-tree-select label="Warehouse region" formControlName="region" [nodes]="regions" />
      <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 TreeSelectReactiveFormsDemo {
  protected readonly regions = REGIONS;
  protected readonly form = new FormGroup({
    // Validators.required treats an empty array as missing.
    region: new FormControl<readonly string[]>([], {
      nonNullable: true,
      validators: 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="tree-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="tree-select"]`

| Part | Element | data-state |
| --- | --- | --- |
| `field` | Positioned wrapper of the label, trigger and buttons. |   |
| `label` | The visible (or floating) label. |   |
| `trigger` | The `role="combobox"` element. | `open, closed` |
| `value` | The selected label, comma list or "{0} selected" summary. |   |
| `chip` | A `vig-chip` per shown value (`display="chip"`). |   |
| `placeholder` | The placeholder text in the trigger. |   |
| `indicator` | The chevron. |   |
| `clear` | The clear button (`clearable`). |   |
| `panel` | The `role="dialog"` panel, in the overlay container; the tree in it keeps the Tree parts. |   |
| `filter` | The search field at the top of the panel (`filter`). |   |
| `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 a `role="combobox"` labelled by the field label, with `aria-haspopup="dialog"` and `aria-expanded`; its panel is a `role="dialog"` named like the field, holding the search field and a `vig-tree` with all of its keyboard support.
- ArrowDown, ArrowUp, Enter or Space open the panel and move focus to the selected node (or the first one), or to the search field with `filter`; ArrowDown in the search field moves on to the tree. Escape closes the panel and returns focus to the trigger; Tab closes it and moves on from the trigger.
- Texts are translated with the locale or per instance through `labels` (`clearAriaLabel`, `removeAriaLabel`, `filterAriaLabel`, `selectedItemsLabel` and the tree's loading, error and empty texts).

## API

### TreeSelect

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

A form field whose panel holds a `vig-tree`: pick one node (`single`), several (`multiple`), or check whole branches (`checkbox`). The value is always an array of node keys, so switching mode never changes its type and it survives reloading the data. Several values show as text or chips (`display`), and `filter` adds a search field above the tree.

**Example :**

```html
<vig-tree-select label="Category" [nodes]="categories" [formField]="form.category" />
```

The trigger is a combobox opening a dialog (`aria-haspopup="dialog"`): focus moves into the tree (or its search field), Escape closes it and returns to the trigger. 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). data-opening data-closing

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `cascade` | `boolean` | `true` | `checkbox` mode: checking a node checks its branch; parents follow their children. |
| `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` | `"comma" \| "chip"` | `'comma'` | Several values: `comma`-separated text, or removable `chip`s. |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `filter` | `boolean` | `false` | Adds a search field above the tree; matches show with their ancestors. |
| `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` | — |
| `keyLabel` | `((key: string) => string \| undefined) \| undefined` | `undefined` | Labels a selected key whose node is not known: not loaded yet (under a lazy node) or gone from `nodes`. Without it, or when it returns `undefined`, the trigger shows the key itself. Such keys stay in the value when an ancestor is unchecked, since the field cannot tell that they lie below it. |
| `label` (required) | `string` | — | — |
| `labelPosition` | `LabelPosition` | `'float'` | `float` (default) rests the label inside the field; `top` sets it above. |
| `labels` | `Partial<TreeSelectLabels>` | — | Texts (i18n); locale defaults. |
| `loadChildren` | `TreeLoader<T> \| undefined` | `undefined` | Fetches the children of nodes that have none of their own; see `TreeLoader`. |
| `maxSelectedLabels` | `number` | `3` | Above this many values the trigger shows `selectedItemsLabel` instead. |
| `name` | `string` | `''` | — |
| `nodes` | `readonly TreeNode<T>[]` | `[]` | The top-level nodes. |
| `pending` | `boolean` | `false` | — |
| `placeholder` | `string \| undefined` | `undefined` | Shown in the trigger while nothing is selected. |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `selectionMode` | `TreeSelectMode` | `'single'` | `single` (closes on pick), `multiple` or `checkbox`. |
| `size` | `FieldSize` | `'md'` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `readonly string[]` | `[]` | Keys of the selected nodes; empty when nothing is selected. |
| `virtual` | `boolean` | `false` | Renders only the rows in view in the panel's tree, for large trees (see `vig-tree`). |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `touch` | `void` | — |
| `valueChange` | `readonly string[]` | Keys of the selected nodes; empty when nothing is selected. |

#### 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`. |
