# Select button

A segmented control for picking one of two to five short options, such as a time period or a view mode. It is single-choice; for several values use a multi select.

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

```typescript title="Import"
import { SelectButton } from '@vigdx/ui/select-button';
import { SelectOptionTemplate } from '@vigdx/ui/select';
```

## Basic

Pass `options` as `SelectOption` objects and bind `[(value)]`. Clicking a segment selects it; as the segments are native radios, the arrow keys move and select in one step, following the visual order in right-to-left layouts.

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

type Period = 'day' | 'week' | 'month' | 'year';

@Component({
  selector: 'app-select-button-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [SelectButton],
  template: `
    <vig-select-button label="Period" [options]="periods" [(value)]="period" />
    <p class="text-sm text-muted-foreground">Showing totals per {{ period() ?? '…' }}.</p>
  `,
})
export class SelectButtonBasicDemo {
  protected readonly periods: SelectOption<Period>[] = [
    { value: 'day', label: 'Day' },
    { value: 'week', label: 'Week' },
    { value: 'month', label: 'Month' },
    { value: 'year', label: 'Year' },
  ];
  protected readonly period = signal<Period | null>('week');
}
```

## Icons and custom content

`icon` names a registered icon shown before the label. For other content, an `<ng-template vigSelectOption let-option>` replaces the icon and label of each segment.

```typescript title="select-button-icons.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Icon } from '@vigdx/ui/icon';
import { SelectOptionTemplate, type SelectOption } from '@vigdx/ui/select';
import { SelectButton } from '@vigdx/ui/select-button';

@Component({
  selector: 'app-select-button-icons',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Icon, SelectButton, SelectOptionTemplate],
  template: `
    <div class="flex flex-col gap-6">
      <vig-select-button label="Status" value="active" [options]="statuses" />

      <vig-select-button label="Sort" value="asc" [options]="sort">
        <ng-template vigSelectOption let-option>
          <vig-icon [name]="option.value === 'asc' ? 'arrow-up' : 'arrow-down'" />
          <span>{{ option.label }}</span>
        </ng-template>
      </vig-select-button>
    </div>
  `,
})
export class SelectButtonIconsDemo {
  // `icon` names a registered glyph shown before the label.
  protected readonly statuses: SelectOption[] = [
    { value: 'active', label: 'Active', icon: 'success' },
    { value: 'paused', label: 'Paused', icon: 'warning' },
    { value: 'failed', label: 'Failed', icon: 'error' },
  ];
  protected readonly sort: SelectOption[] = [
    { value: 'asc', label: 'Oldest first' },
    { value: 'desc', label: 'Newest first' },
  ];
}
```

## Allow empty

With `allowEmpty`, clicking the selected segment again clears the value to `null`. Useful for optional filters.

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

@Component({
  selector: 'app-select-button-allow-empty',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [SelectButton],
  template: `
    <vig-select-button
      label="Priority"
      hint="Click the selected priority again to clear the filter."
      [options]="priorities"
      [allowEmpty]="true"
      [(value)]="priority"
    />
    <p class="text-sm text-muted-foreground">Filter: {{ priority() ?? 'all priorities' }}</p>
  `,
})
export class SelectButtonAllowEmptyDemo {
  protected readonly priorities: SelectOption[] = [
    { value: 'low', label: 'Low' },
    { value: 'medium', label: 'Medium' },
    { value: 'high', label: 'High' },
  ];
  protected readonly priority = signal<string | null>('high');
}
```

## Without a visible label

In a toolbar the context often names the control. Leave out `label` and set `ariaLabel`, which names the group for screen readers.

```typescript title="select-button-toolbar.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { type SelectOption } from '@vigdx/ui/select';
import { SelectButton } from '@vigdx/ui/select-button';

@Component({
  selector: 'app-select-button-toolbar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [SelectButton],
  template: `
    <div class="flex flex-wrap items-center justify-between gap-3">
      <h3 class="text-base font-semibold text-foreground">Orders</h3>
      <!-- No visible label: ariaLabel names the group. -->
      <vig-select-button ariaLabel="Order view" value="list" [options]="views" />
    </div>
  `,
})
export class SelectButtonToolbarDemo {
  protected readonly views: SelectOption[] = [
    { value: 'list', label: 'List' },
    { value: 'board', label: 'Board' },
    { value: 'calendar', label: 'Calendar', icon: 'calendar' },
  ];
}
```

## Disabled, read-only and error

An option with `disabled: true` is skipped by the arrow keys. `disabled` disables every segment, `readonly` keeps them focusable but ignores selection, and errors show once the field is `touched` and `invalid`.

```typescript title="select-button-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { type SelectOption } from '@vigdx/ui/select';
import { SelectButton } from '@vigdx/ui/select-button';

@Component({
  selector: 'app-select-button-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [SelectButton],
  template: `
    <div class="flex flex-col gap-6">
      <vig-select-button label="Disabled option" value="standard" [options]="withDisabled" />
      <vig-select-button label="Disabled" value="standard" [options]="plans" [disabled]="true" />
      <vig-select-button label="Read-only" value="standard" [options]="plans" [readonly]="true" />
      <vig-select-button
        label="Delivery"
        [options]="plans"
        [required]="true"
        [touched]="true"
        [invalid]="true"
        [errors]="[{ kind: 'required' }]"
        [errorMessages]="{ required: 'Choose a delivery option.' }"
      />
    </div>
  `,
})
export class SelectButtonStatesDemo {
  protected readonly plans: SelectOption[] = [
    { value: 'standard', label: 'Standard' },
    { value: 'express', label: 'Express' },
    { value: 'overnight', label: 'Overnight' },
  ];
  protected readonly withDisabled: SelectOption[] = [
    ...this.plans.slice(0, 2),
    { value: 'overnight', label: 'Overnight', disabled: true },
  ];
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`. The field counts as touched once focus leaves the whole group.

```typescript title="select-button-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 { type SelectOption } from '@vigdx/ui/select';
import { SelectButton } from '@vigdx/ui/select-button';

@Component({
  selector: 'app-select-button-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe, ReactiveFormsModule, Button, SelectButton, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" [formGroup]="form" (ngSubmit)="submit()">
      <vig-select-button label="Size" formControlName="size" [options]="sizes" />
      <div class="flex gap-2">
        <vig-button type="submit" label="Add to cart" />
        <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 SelectButtonReactiveFormsDemo {
  protected readonly sizes: SelectOption[] = [
    { value: 's', label: 'S' },
    { value: 'm', label: 'M' },
    { value: 'l', label: 'L' },
    { value: 'xl', label: 'XL', disabled: true },
  ];
  protected readonly form = new FormGroup({
    size: new FormControl<string | null>(null, Validators.required),
  });

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

## Signal Forms

`vig-select-button` implements `FormValueControl<T | null>`, so `[formField]` binds value and validation.

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

type Theme = 'light' | 'dark' | 'system';

@Component({
  selector: 'app-select-button-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, SelectButton],
  template: `
    <vig-select-button label="Theme" [options]="themes" [formField]="settings.theme" />
    <p class="text-sm text-muted-foreground">Theme: {{ model().theme }}</p>
  `,
})
export class SelectButtonSignalFormsDemo {
  protected readonly themes: SelectOption<Theme>[] = [
    { value: 'light', label: 'Light' },
    { value: 'dark', label: 'Dark' },
    { value: 'system', label: 'System' },
  ];
  protected readonly model = signal<{ theme: Theme | null }>({ theme: 'system' });
  protected readonly settings = form(this.model, (path) => {
    required(path.theme);
  });
}
```

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

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible group label. |   |
| `group` | The `role="radiogroup"` segment bar. |   |
| `option` | One segment `<label>`. | `checked, unchecked` |
| `input` | The visually hidden radio of a segment. |   |
| `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

- Each segment is a `<label>` around a visually hidden native `<input type="radio">` in a `role="radiogroup"`, like `vig-radio-group`: the single tab stop, the arrow keys (which move and select) and right-to-left order come from the browser.
- The selected segment has a primary border besides its raised background, and switches to the system Highlight colors in forced-colors mode; the focus ring is drawn on the segment.
- Give the group a name: a visible `label`, or `ariaLabel` when there is none.
- `required`, `readonly` and an invalid state set `aria-required`, `aria-readonly` and `aria-invalid` on the group; hint and error are linked through `aria-describedby`.
- Segment labels are the accessible names, so keep them short but self-explanatory; icons are decorative.

## API

### SelectButton

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

Segmented control for a small exclusive choice (PrimeNG p-selectbutton territory). Each segment is a `<label>` around a visually hidden native `<input type="radio">` sharing one `name`, so the single tab stop, arrow keys (which move and select) and form semantics come from the browser — like `vig-radio-group`, with a segmented look. Deliberately single-select; multi-pick lists belong to vig-multi-select.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `allowEmpty` | `boolean` | `false` | Clicking the selected segment deselects it (value becomes null). |
| `ariaLabel` | `string \| undefined` | `undefined` | — |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` | `string` | `''` | Visible group label; omit for toolbar use and pass `ariaLabel` instead. |
| `name` | `string` | `''` | — |
| `options` | `readonly SelectOption<T>[]` | `[]` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `required` | `boolean` | `false` | — |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `T \| null` | `null` | — |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `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` | Returns the control to its pristine look: drops in-progress text, closes an open popup, clears errors the component raised itself and the submitted state of `errorDisplay: 'interacted'`. Signal Forms calls it from `field().reset()`; `VigValueAccessor` from `control.reset()`. It never changes the value: the bound form owns that. |

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