Formularios

Select

Muestra una lista de opciones para que el usuario elija, activada por un botón.

Ejemplo

Value: none

El ejemplo de arriba es este archivo, renderizado en vivo:

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 nativo

Una alternativa más ligera a volt-select para casos sencillos: es el elemento <select> nativo de verdad (comportamiento completo del selector móvil/nativo, funciona con formControl/ngModel sin más), con estilo acorde al tema.

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

Zona de pruebas

Cambia los inputs e interactúa con la vista previa: el panel de eventos muestra lo que emite el componente y el código sigue tus ajustes.

volt-select

Value: —

Entradas

Eventos

Aún no hay eventos. Interactúa con la vista previa para verlos aquí.

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 — vista previa ampliada

Formularios y accesibilidad

  • El disparador es un <button role="combobox"> nativo con aria-expanded y, mientras está abierto, aria-controls apuntando al popup role="listbox" y aria-activedescendant a la role="option" activa. Las opciones seleccionadas llevan aria-selected="true"; las deshabilitadas, aria-disabled="true".
  • Nómbralo con un <volt-label> dentro de <volt-form-field> o con aria-label. required fija aria-required.
  • Teclado: las flechas lo abren y recorren las opciones (saltando las deshabilitadas), Inicio y Fin van a la primera y la última mientras está abierto, Enter o Espacio seleccionan, Escape cierra y el foco vuelve al disparador. Escribir una letra no salta a ninguna opción (no hay búsqueda incremental); usa Listbox o Combobox cuando la lista sea larga.
  • El popup se añade a <body> (container) y se voltea para seguir dentro de la ventana (flip); se elimina cuando el select se cierra o se destruye.
  • Con Forms, una selección notifica el valor una sola vez. El control se marca como tocado cuando el foco sale del select —no cuando una pulsación del puntero lleva el foco al popup—, así que un select obligatorio no muestra su error mientras el usuario está eligiendo.
  • El disparador muestra el valor mediante displayWith (por defecto String(value)), porque las etiquetas de las opciones no se renderizan con el popup cerrado. Pasa displayWith para mostrar una etiqueta.
  • Punto de entrada de Quartz: mismo contrato, sin container, scrollToOption ni allOptions.

Referencia de la API

VoltNativeSelect — select[voltNativeSelect]

EntradaTipoPor defecto
disabled boolean false
class string ''
id string —

VoltSelectContent — volt-select-content

EntradaTipoPor defecto
class string ''

VoltSelectItem — volt-select-item

EntradaTipoPor defecto
value unknown undefined
disabled boolean false
class string ''

VoltSelectLabel — volt-select-label

EntradaTipoPor defecto
class string ''

VoltSelectSeparator — volt-select-separator

EntradaTipoPor defecto
class string ''

VoltSelect — volt-select

EntradaTipoPor defecto
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)
SalidaTipo
valueChangeunknown

Instalación

Copia el código en tu proyecto:

npx @voltui/cli add select

O impórtalo desde el paquete:

npm install @voltui/components

Código fuente

Copia este código en tu proyecto. El componente usa 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