Forms
Select
Displays a list of options for the user to pick from—triggered by a button.
Example
Value: none
The example above is this file, rendered live:
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);
}
Native Select
A lighter alternative to volt-select for simple cases: it's the real native <select> element (full mobile/native picker behavior, works with formControl/ngModel for free), styled to match the theme.
Value: apple
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 });
}
Playground
Change the inputs and interact with the preview: the events panel shows what the component emits, and the code follows your settings.
volt-select
Value: —
No events yet. Interact with the preview to see them here.
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>Forms and accessibility
- The trigger is a native
<button role="combobox">witharia-expandedand, while open,aria-controlspointing at therole="listbox"popup andaria-activedescendantat the activerole="option". Selected options carryaria-selected="true"; disabled onesaria-disabled="true". - Name it with a
<volt-label>inside<volt-form-field>or witharia-label.requiredsetsaria-required. - Keyboard: Arrow keys open it and move through the options (skipping disabled ones), Home and End jump to the first and last while it is open, Enter or Space selects, Escape closes, and focus returns to the trigger. Typing a letter does not jump to an option (no typeahead); use Listbox or Combobox when the list is long.
- The popup is appended to
<body>(container) and flips to stay in the viewport (flip); it is removed when the select closes or is destroyed. - With Forms, a selection reports the value once. The control is marked touched when focus leaves the select — not when a pointer press moves focus into the popup — so a required select does not flash its error while the reader is choosing.
- The trigger shows the value through
displayWith(by defaultString(value)), because the option labels are not rendered while the popup is closed. PassdisplayWithto show a label. - Quartz entry point: same contract, without
container,scrollToOptionandallOptions.
API Reference
VoltNativeSelect — select[voltNativeSelect]
| Input | Type | Default |
|---|---|---|
| disabled | boolean | false |
| class | string | '' |
| id | string | — |
VoltSelectContent — volt-select-content
| Input | Type | Default |
|---|---|---|
| class | string | '' |
VoltSelectItem — volt-select-item
| Input | Type | Default |
|---|---|---|
| value | unknown | undefined |
| disabled | boolean | false |
| class | string | '' |
VoltSelectLabel — volt-select-label
| Input | Type | Default |
|---|---|---|
| class | string | '' |
VoltSelectSeparator — volt-select-separator
| Input | Type | Default |
|---|---|---|
| class | string | '' |
VoltSelect — volt-select
| Input | Type | Default |
|---|---|---|
| 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) |
| Output | Type |
|---|---|
| valueChange | unknown |
Installation
Copy the source into your project:
npx @voltui/cli add select
Or import it from the package:
npm install @voltui/components
Source
Copy this code to your project. The component uses ng-primitives/select.
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);
}
}
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();
}
}
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();
}
}