Форми

Select

Показує список варіантів на вибір, який відкриває кнопка.

Приклад

Value: none

Приклад вище — це цей файл, відрендерений наживо:

select-example.ts
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import {
  VoltFormField,
  VoltLabel,
  VoltSelect,
  VoltSelectContent,
  VoltSelectItem,
  VoltSelectLabel,
  VoltSelectSeparator,
} from '@voltui/components';

@Component({
  selector: 'app-select-example',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [
    VoltFormField,
    VoltLabel,
    VoltSelect,
    VoltSelectContent,
    VoltSelectItem,
    VoltSelectLabel,
    VoltSelectSeparator,
  ],
  template: `
    <volt-form-field class="mx-auto max-w-xs">
      <volt-label>Produce</volt-label>
      <volt-select placeholder="Select a fruit" [(value)]="produce" [displayWith]="label">
        <volt-select-content>
          <volt-select-label>Fruits</volt-select-label>
          <volt-select-item value="apple">Apple</volt-select-item>
          <volt-select-item value="banana">Banana</volt-select-item>
          <volt-select-item value="blueberry">Blueberry</volt-select-item>
          <volt-select-separator />
          <volt-select-label>Vegetables</volt-select-label>
          <volt-select-item value="carrot">Carrot</volt-select-item>
          <volt-select-item value="spinach" disabled>Spinach</volt-select-item>
        </volt-select-content>
      </volt-select>
      <p class="text-sm text-muted-foreground">
        Value: <code class="text-foreground">{{ produce() ?? 'none' }}</code>
      </p>
    </volt-form-field>
  `,
})
export class SelectExample {
  readonly produce = signal<string | undefined>(undefined);
  /** The trigger shows the value unless told how to label it. */
  readonly label = (value: unknown) =>
    String(value).charAt(0).toUpperCase() + String(value).slice(1);
}

View source

Нативний select

Легша альтернатива до volt-select для простих випадків: це справжній нативний елемент <select> (повна поведінка мобільного та системного вибору, працює з formControl/ngModel без зусиль), стилізований під тему.

Value: apple

native-select-example.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { VoltLabel, VoltNativeSelect } from '@voltui/components';

/** The real `<select>`: the platform's own picker, keyboard and form behavior. */
@Component({
  selector: 'app-native-select-example',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, VoltLabel, VoltNativeSelect],
  template: `
    <div class="mx-auto max-w-xs space-y-3">
      <volt-label htmlFor="fruit">Fruit</volt-label>
      <select id="fruit" voltNativeSelect [formControl]="fruit">
        <option value="apple">Apple</option>
        <option value="banana">Banana</option>
        <option value="blueberry">Blueberry</option>
      </select>
      <p class="text-sm text-muted-foreground">
        Value: <code class="text-foreground">{{ fruit.value }}</code>
      </p>
    </div>
  `,
})
export class NativeSelectExample {
  readonly fruit = new FormControl('apple', { nonNullable: true });
}

View source

Пісочниця

Змінюйте вхідні параметри та взаємодійте з попереднім переглядом: панель подій показує, що випромінює компонент, а код відповідає вашим налаштуванням.

volt-select

Value: —

Вхідні параметри

Події

Подій ще немає. Взаємодійте з попереднім переглядом, щоб побачити їх тут.

HTML

<volt-select [(value)]="plan" placeholder="Choose a plan" />
  <volt-select-content>
    <volt-select-item value="free">Free</volt-select-item>
    <volt-select-item value="team" disabled>Team</volt-select-item>
    <volt-select-item value="pro">Pro</volt-select-item>
  </volt-select-content>
</volt-select>

volt-select — розгорнутий попередній перегляд

Форми та доступність

  • Тригер — це нативний <button role="combobox"> з aria-expanded, а поки список відкритий — з aria-controls, що вказує на спливний role="listbox", і aria-activedescendant — на активний role="option". Вибрані варіанти мають aria-selected="true", вимкнені — aria-disabled="true".
  • Назвіть його через <volt-label> усередині <volt-form-field> або через aria-label. required задає aria-required.
  • Клавіатура: стрілки відкривають список і переміщують між варіантами (пропускаючи вимкнені), Home і End переходять до першого й останнього, поки список відкритий, Enter або пробіл вибирають, Escape закриває, і фокус повертається на тригер. Введення літери не переходить до варіанта (пошуку за першими символами немає); для довгих списків використовуйте Listbox або Combobox.
  • Спливний список додається до <body> (container) і перевертається, щоб лишатися у вікні (flip); він видаляється, коли select закривається або знищується.
  • З Forms вибір повідомляє значення один раз. Елемент керування позначається торкнутим, коли фокус залишає select, — а не коли натискання вказівником переносить фокус у список, — тож обов’язковий select не показує помилку, поки користувач вибирає.
  • Тригер показує значення через displayWith (за замовчуванням String(value)), бо підписи варіантів не рендеряться, поки список закритий. Передайте displayWith, щоб показати підпис.
  • Точка входу Quartz: той самий контракт, без container, scrollToOption і allOptions.

Довідник API

VoltNativeSelect — select[voltNativeSelect]

ВхідТипЗа замовчуванням
disabled boolean false
class string ''
id string —

VoltSelectContent — volt-select-content

ВхідТипЗа замовчуванням
class string ''

VoltSelectItem — volt-select-item

ВхідТипЗа замовчуванням
value unknown undefined
disabled boolean false
class string ''

VoltSelectLabel — volt-select-label

ВхідТипЗа замовчуванням
class string ''

VoltSelectSeparator — volt-select-separator

ВхідТипЗа замовчуванням
class string ''

VoltSelect — volt-select

ВхідТипЗа замовчуванням
placeholder string 'Select an option'
ariaLabel string ''
aria-label string | undefined undefined
class string ''
value unknown undefined
disabled boolean false
multiple boolean false
required boolean false
compareWith (a: unknown, b: unknown) => boolean Object.is
dropdownPlacement Placement 'bottom-start'
container string | HTMLElement | null 'body'
flip NgpFlipInput true
scrollToOption ((index: number) => void) | undefined undefined
allOptions unknown[] | undefined undefined
displayWith (value: unknown) => string value => String(value)
ВихідТип
valueChangeunknown

Встановлення

Скопіюйте вихідний код у свій проєкт:

npx @voltui/cli add select

Або імпортуйте його з пакета:

npm install @voltui/components

Вихідний код

Скопіюйте цей код у свій проєкт. Компонент використовує ng-primitives/select.

select.ts
import {
  afterNextRender,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DOCUMENT,
  ElementRef,
  forwardRef,
  inject,
  Injector,
  input,
  model,
  signal,
  viewChild,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import type { Placement } from '@floating-ui/dom';
import { NgpSelect, NgpSelectPortal, provideSelectState } from 'ng-primitives/select';
import type { NgpFlipInput } from 'ng-primitives/portal';
import { injectFormControlState } from '../../form-control-state';
import { forwardAttributesFromHost, forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';

const HOST_CLASSES = 'block w-full';

/**
 * Custom select with a native `<button>` trigger. `class` and `aria-label` belong to the trigger:
 * they are applied there and removed from the host, which stays a full-width block.
 */
@Component({
  selector: 'volt-select',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: HOST_CLASSES,
  },
  imports: [NgpSelect, NgpSelectPortal],
  providers: [
    provideSelectState(),
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => VoltSelect),
      multi: true,
    },
  ],
  template: `
    <button
      ngpSelect
      type="button"
      [ngpSelectDropdownPlacement]="dropdownPlacement()"
      [ngpSelectValue]="value()"
      [ngpSelectDisabled]="isDisabled()"
      [ngpSelectMultiple]="multiple()"
      [ngpSelectCompareWith]="compareWith()"
      [ngpSelectDropdownContainer]="container()"
      [ngpSelectDropdownFlip]="flip()"
      [ngpSelectScrollToOption]="scrollToOption()"
      [ngpSelectOptions]="allOptions()"
      [attr.aria-label]="ariaLabel() || ariaLabelAttribute() || null"
      [attr.aria-required]="required() ? 'true' : null"
      [attr.aria-invalid]="formControlState.invalid() ? 'true' : null"
      (ngpSelectValueChange)="onValueChange($event)"
      (ngpSelectOpenChange)="onOpenChange($event)"
      (blur)="onTriggerBlur($event)"
      [class]="triggerClasses()"
    >
      <span class="block text-left truncate flex-1 pointer-events-none">
        @if (isEmpty()) {
          <span class="text-muted-foreground">{{ placeholder() }}</span>
        } @else {
          {{ displayValue(value()) }}
        }
      </span>
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        class="h-4 w-4 opacity-50 shrink-0 pointer-events-none"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    </button>

    <ng-template ngpSelectPortal>
      <ng-content />
    </ng-template>
  `,
})
export class VoltSelect implements ControlValueAccessor {
  protected readonly formControlState = injectFormControlState();

  readonly placeholder = input('Select an option');
  readonly ariaLabel = input('');
  /** Same as `ariaLabel`, for the attribute spelling consumers write naturally. */
  // eslint-disable-next-line @angular-eslint/no-input-rename -- `ariaLabel` (1.0) already owns the camelCase name
  readonly ariaLabelAttribute = input<string | undefined>(undefined, { alias: 'aria-label' });
  /** Classes for the trigger button, merged over the defaults with `cn()`. */
  readonly class = input<string>('');
  readonly value = model<unknown>(undefined);
  readonly disabled = input<boolean, unknown>(false, { transform: booleanAttribute });
  readonly multiple = input<boolean, unknown>(false, { transform: booleanAttribute });
  /** Exposes `aria-required` on the trigger. With `formControl`/`ngModel` it also adds Angular's required validator. */
  readonly required = input<boolean, unknown>(false, { transform: booleanAttribute });
  readonly compareWith = input<(a: unknown, b: unknown) => boolean>(Object.is);
  readonly dropdownPlacement = input<Placement>('bottom-start');
  readonly container = input<string | HTMLElement | null>('body');
  readonly flip = input<NgpFlipInput, NgpFlipInput>(true, {
    transform: (value: NgpFlipInput) => {
      if (typeof value === 'string') {
        return value === 'true';
      }
      return value;
    },
  });
  readonly scrollToOption = input<((index: number) => void) | undefined>(undefined);
  readonly allOptions = input<unknown[] | undefined>(undefined);
  readonly displayWith = input<(value: unknown) => string>(value => String(value));

  private readonly controlDisabled = signal(false);
  protected readonly isDisabled = computed(() => this.disabled() || this.controlDisabled());

  protected readonly triggerClasses = computed(() =>
    cn(
      'flex h-control-md w-full items-center justify-between rounded-md border-(length:--volt-control-border-width) border-input bg-background px-inset-sm py-2 text-sm ring-offset-background cursor-pointer placeholder:text-muted-foreground focus:outline-hidden focus:ring-(length:--ring-width) focus:ring-ring focus:ring-offset-(length:--ring-offset-width) disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
      this.class()
    )
  );

  private onChange: (value: unknown) => void = () => {};
  protected onTouched: () => void = () => {};

  constructor() {
    forwardClassFromHost(HOST_CLASSES);
    forwardAttributesFromHost('aria-label');
  }

  private readonly trigger = viewChild.required(NgpSelect);
  private readonly triggerElement = viewChild.required(NgpSelect, { read: ElementRef });
  private readonly document = inject(DOCUMENT);
  private readonly injector = inject(Injector);

  /**
   * Touched means the reader left the field. A pointer press on an option moves focus from the trigger
   * into the popup, which blurred the trigger before the value was committed: a required select was
   * reported touched and invalid while the reader was still choosing, flashing its error (and
   * announcing an alert). Focus that moves into this select's own popup is not leaving the field.
   */
  protected onTriggerBlur(event: FocusEvent): void {
    const next = event.relatedTarget;
    const popupId = this.triggerElement().nativeElement.getAttribute('aria-controls');
    const popup = popupId ? this.document.getElementById(popupId) : null;
    if (popup && next instanceof Node && popup.contains(next)) return;
    this.onTouched();
  }

  /** The popup closed while focus was inside it and then moved elsewhere (a click outside): left the field. */
  protected onOpenChange(open: boolean): void {
    if (open) return;
    afterNextRender(
      () => {
        const active = this.document.activeElement;
        const trigger = this.triggerElement().nativeElement;
        const elsewhere =
          !!active &&
          active !== trigger &&
          active !== this.document.body &&
          active.isConnected &&
          !active.closest('[role="listbox"]');
        if (elsewhere) this.onTouched();
      },
      { injector: this.injector }
    );
  }

  protected onValueChange(value: unknown): void {
    this.value.set(value);
    this.onChange(value);
    if (!this.multiple()) this.restoreFocusAfterClose();
  }

  /** Nothing selected: `undefined`, `null` or an empty array — not every falsy value (`0`, `''`). */
  protected readonly isEmpty = computed(() => {
    const value = this.value();
    return value === undefined || value === null || (Array.isArray(value) && value.length === 0);
  });

  /**
   * A pointer selection closes the popup while focus sits on the clicked option, which is then
   * removed, so focus fell to <body>; the combobox pattern returns it to the trigger. Runs after the
   * next render, and only when focus is lost (on the closing popup or on <body>) — focus the user
   * moved elsewhere is left alone.
   */
  private restoreFocusAfterClose(): void {
    afterNextRender(
      () => {
        const active = this.document.activeElement;
        const lost =
          !active ||
          active === this.document.body ||
          !active.isConnected ||
          // still on an option of the popup that is closing (it leaves after its exit animation)
          !!active.closest('[role="listbox"]');
        if (lost) this.trigger().focus();
      },
      { injector: this.injector }
    );
  }

  protected displayValue(value: unknown): string {
    if (Array.isArray(value)) {
      return value.map(item => this.displayWith()(item)).join(', ');
    }

    return this.displayWith()(value);
  }

  writeValue(value: unknown): void {
    this.value.set(value);
  }

  registerOnChange(fn: (value: unknown) => void): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.controlDisabled.set(isDisabled);
  }
}

View source

select-content.ts
import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core';
import { NgpSelectDropdown } from 'ng-primitives/select';
import { forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';
import { VoltThemeInherit } from '../theme/theme-scope';

@Component({
  selector: 'volt-select-content',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgpSelectDropdown, VoltThemeInherit],
  template: `
    <div ngpSelectDropdown voltThemeInherit [class]="classes()">
      <div class="p-1 w-full flex flex-col">
        <ng-content />
      </div>
    </div>
  `,
})
export class VoltSelectContent {
  /** Classes for the inner element, merged over the defaults with `cn()`. */
  readonly class = input<string>('');

  protected readonly classes = computed(() =>
    cn(
      'absolute block z-50 min-w-[var(--ngp-select-width)] max-w-[var(--ngp-select-width)] w-full overflow-hidden rounded-md border-(length:--border-width) border-border bg-popover text-popover-foreground shadow-md animate-in fade-in-80 zoom-in-95',
      this.class()
    )
  );

  constructor() {
    forwardClassFromHost();
  }
}

View source

select-item.ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  input,
  computed,
} from '@angular/core';
import { NgpSelectOption } from 'ng-primitives/select';
import { forwardClassFromHost } from '../../host-forwarding';
import { cn } from '../../utils';

@Component({
  selector: 'volt-select-item',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgpSelectOption],
  template: `
    <div
      ngpSelectOption
      [ngpSelectOptionValue]="value()"
      [ngpSelectOptionDisabled]="disabled()"
      [attr.aria-disabled]="disabled() ? 'true' : null"
      [class]="classes()"
    >
      <span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          class="h-4 w-4 hidden group-data-[selected]:block"
        >
          <path d="M20 6 9 17l-5-5" />
        </svg>
      </span>
      <ng-content />
    </div>
  `,
})
export class VoltSelectItem {
  readonly value = input<unknown>(undefined);
  readonly disabled = input(false, { transform: booleanAttribute });

  /** Classes for the inner element, merged over the defaults with `cn()`. */
  readonly class = input<string>('');

  protected readonly classes = computed(() =>
    cn(
      'group relative flex w-full cursor-pointer select-none items-center rounded-sm py-item-y pl-8 pr-2 text-sm outline-hidden focus:bg-muted focus:text-muted-foreground aria-disabled:pointer-events-none aria-disabled:opacity-50 transition-colors',
      this.class()
    )
  );

  constructor() {
    forwardClassFromHost();
  }
}

View source