- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Carousel
- Checkbox
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Icon
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Menubar
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner (Toast)
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toggle
- Toggle Group
- Tooltip
Select
Select a value from a list of options.
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-preview',
imports: [HlmSelectImports],
template: `
<hlm-select [itemToString]="itemToString">
<hlm-select-trigger class="w-56">
<hlm-select-value placeholder="Select a fruit" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (item of items; track item.value) {
<hlm-select-item [value]="item.value">{{ item.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class SelectPreview {
public readonly items = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
public readonly itemToString = (value: string) => this.items.find((item) => item.value === value)?.label || '';
}Installation
ng g @spartan-ng/cli:ui selectnx g @spartan-ng/cli:ui selectimport { DestroyRef, ElementRef, HostAttributeToken, Injector, PLATFORM_ID, effect, inject, runInInjectionContext } from '@angular/core';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
import { twMerge } from 'tailwind-merge';
export function hlm(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// Global map to track class managers per element
const elementClassManagers = new WeakMap<HTMLElement, ElementClassManager>();
// Global mutation observer for all elements
let globalObserver: MutationObserver | null = null;
const observedElements = new Set<HTMLElement>();
interface ElementClassManager {
element: HTMLElement;
sources: Map<number, { classes: Set<string>; order: number }>;
baseClasses: Set<string>;
isUpdating: boolean;
nextOrder: number;
hasInitialized: boolean;
restoreRafId: number | null;
/** Transitions are suppressed until the first effect writes correct classes */
transitionsSuppressed: boolean;
/** Original inline transition value to restore after suppression (empty string = none was set) */
previousTransition: string;
/** Original inline transition priority to preserve !important when restoring */
previousTransitionPriority: string;
}
let sourceCounter = 0;
/**
* This function dynamically adds and removes classes for a given element without requiring
* the a class binding (e.g. `[class]="..."`) which may interfere with other class bindings.
*
* 1. This will merge the existing classes on the element with the new classes.
* 2. It will also remove any classes that were previously added by this function but are no longer present in the new classes.
* 3. Multiple calls to this function on the same element will be merged efficiently.
*/
export function classes(computed: () => ClassValue[] | string, options: ClassesOptions = {}) {
runInInjectionContext(options.injector ?? inject(Injector), () => {
const elementRef = options.elementRef ?? inject(ElementRef);
const platformId = inject(PLATFORM_ID);
const destroyRef = inject(DestroyRef);
const baseClasses = inject(new HostAttributeToken('class'), { optional: true });
const element = elementRef.nativeElement;
// Create unique identifier for this source
const sourceId = sourceCounter++;
// Get or create the class manager for this element
let manager = elementClassManagers.get(element);
if (!manager) {
// Initialize base classes from variation (host attribute 'class')
const initialBaseClasses = new Set<string>();
if (baseClasses) {
toClassList(baseClasses).forEach((cls) => initialBaseClasses.add(cls));
}
manager = {
element,
sources: new Map(),
baseClasses: initialBaseClasses,
isUpdating: false,
nextOrder: 0,
hasInitialized: false,
restoreRafId: null,
transitionsSuppressed: false,
previousTransition: '',
previousTransitionPriority: '',
};
elementClassManagers.set(element, manager);
// Setup global observer if needed and register this element
setupGlobalObserver(platformId);
observedElements.add(element);
// Suppress transitions until the first effect writes correct classes and
// the browser has painted them. This prevents CSS transition animations
// during hydration when classes change from SSR state to client state.
if (isPlatformBrowser(platformId)) {
manager.previousTransition = element.style.getPropertyValue('transition');
manager.previousTransitionPriority = element.style.getPropertyPriority('transition');
element.style.setProperty('transition', 'none', 'important');
manager.transitionsSuppressed = true;
}
}
// Assign order once at registration time
const sourceOrder = manager.nextOrder++;
function updateClasses(): void {
// Get the new classes from the computed function
const newClasses = toClassList(computed());
// Update this source's classes, keeping the original order
manager!.sources.set(sourceId, {
classes: new Set(newClasses),
order: sourceOrder,
});
// Update the element
updateElement(manager!);
// Re-enable transitions after the first effect writes correct classes.
// Deferred to next animation frame so the browser paints the class change
// with transitions disabled first, then re-enables them.
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
manager!.restoreRafId = requestAnimationFrame(() => {
manager!.restoreRafId = null;
restoreTransitionSuppression(manager!);
});
}
}
// Register cleanup with DestroyRef
destroyRef.onDestroy(() => {
if (manager!.restoreRafId !== null) {
cancelAnimationFrame(manager!.restoreRafId);
manager!.restoreRafId = null;
}
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
restoreTransitionSuppression(manager!);
}
// Remove this source from the manager
manager!.sources.delete(sourceId);
// If no more sources, clean up the manager
if (manager!.sources.size === 0) {
cleanupManager(element);
} else {
// Update element without this source's classes
updateElement(manager!);
}
});
/**
* We need this effect to track changes to the computed classes. Ideally, we would use
* afterRenderEffect here, but that doesn't run in SSR contexts, so we use a standard
* effect which works in both browser and SSR.
*/
effect(updateClasses);
});
}
function restoreTransitionSuppression(manager: ElementClassManager): void {
const prev = manager.previousTransition;
if (prev) {
manager.element.style.setProperty('transition', prev, manager.previousTransitionPriority || undefined);
} else {
manager.element.style.removeProperty('transition');
}
}
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
function setupGlobalObserver(platformId: Object): void {
if (isPlatformBrowser(platformId) && !globalObserver) {
// Create single global observer that watches the entire document
globalObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const element = mutation.target as HTMLElement;
const manager = elementClassManagers.get(element);
// Only process elements we're managing
if (manager && observedElements.has(element)) {
if (manager.isUpdating) continue; // Ignore changes we're making
// Update base classes to include any externally added classes
const currentClasses = toClassList(element.className);
const allSourceClasses = new Set<string>();
// Collect all classes from all sources
for (const source of manager.sources.values()) {
for (const className of source.classes) {
allSourceClasses.add(className);
}
}
// Any classes not from sources become new base classes
manager.baseClasses.clear();
for (const className of currentClasses) {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
}
updateElement(manager);
}
}
}
});
// Start observing the entire document for class attribute changes
globalObserver.observe(document, {
attributes: true,
attributeFilter: ['class'],
subtree: true, // Watch all descendants
});
}
}
function updateElement(manager: ElementClassManager): void {
if (manager.isUpdating) return; // Prevent recursive updates
manager.isUpdating = true;
// Handle initialization: capture base classes after first source registration
if (!manager.hasInitialized && manager.sources.size > 0) {
// Get current classes on element (may include SSR classes)
const currentClasses = toClassList(manager.element.className);
// Get all classes that will be applied by sources
const allSourceClasses = new Set<string>();
for (const source of manager.sources.values()) {
source.classes.forEach((className) => allSourceClasses.add(className));
}
// Only consider classes as "base" if they're not produced by any source
// This prevents SSR-rendered classes from being preserved as base classes
currentClasses.forEach((className) => {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
});
manager.hasInitialized = true;
}
// Get classes from all sources, sorted by registration order (later takes precedence)
const sortedSources = Array.from(manager.sources.entries()).sort(([, a], [, b]) => a.order - b.order);
const allSourceClasses: string[] = [];
for (const [, source] of sortedSources) {
allSourceClasses.push(...source.classes);
}
// Combine base classes with all source classes, ensuring base classes take precedence
const classesToApply =
allSourceClasses.length > 0 || manager.baseClasses.size > 0
? hlm([...allSourceClasses, ...manager.baseClasses])
: '';
// Apply the classes to the element
if (manager.element.className !== classesToApply) {
manager.element.className = classesToApply;
}
manager.isUpdating = false;
}
function cleanupManager(element: HTMLElement): void {
// Remove from global tracking
observedElements.delete(element);
elementClassManagers.delete(element);
// If no more elements being tracked, cleanup global observer
if (observedElements.size === 0 && globalObserver) {
globalObserver.disconnect();
globalObserver = null;
}
}
interface ClassesOptions {
elementRef?: ElementRef<HTMLElement>;
injector?: Injector;
}
// Cache for parsed class lists to avoid repeated string operations
const classListCache = new Map<string, string[]>();
function toClassList(className: string | ClassValue[]): string[] {
// For simple string inputs, use cache to avoid repeated parsing
if (typeof className === 'string' && classListCache.has(className)) {
return classListCache.get(className)!;
}
const result = clsx(className)
.split(' ')
.filter((c) => c.length > 0);
// Cache string results, but limit cache size to prevent memory growth
if (typeof className === 'string' && classListCache.size < 1000) {
classListCache.set(className, result);
}
return result;
}import type, { ClassValue } from 'clsx';
import { BooleanInput } from '@angular/cdk/coercion';
import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnPopover, BrnPopoverContent, provideBrnPopoverConfig } from '@spartan-ng/brain/popover';
import { BrnSelect, BrnSelectContent, BrnSelectGroup, BrnSelectItem, BrnSelectLabel, BrnSelectMultiple, BrnSelectPlaceholder, BrnSelectScrollDown, BrnSelectScrollUp, BrnSelectSeparator, BrnSelectTrigger, BrnSelectTriggerWrapper, BrnSelectValue, BrnSelectValueTemplate, BrnSelectValues } from '@spartan-ng/brain/select';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, inject, input } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideCheck, lucideChevronDown, lucideChevronUp } from '@ng-icons/lucide';
import { provideBrnDialogDefaultOptions } from '@spartan-ng/brain/dialog';
@Component({
selector: 'hlm-select-content',
imports: [HlmSelectScrollUp, HlmSelectScrollDown],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [BrnSelectContent],
template: `
@if (showScroll()) {
<hlm-select-scroll-up />
}
<div role="listbox" [class]="_computedListboxClasses()">
<ng-content />
</div>
@if (showScroll()) {
<hlm-select-scroll-down />
}
`,
})
export class HlmSelectContent {
protected readonly _computedListboxClasses = computed(() => hlm('flex flex-col'));
public readonly showScroll = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'bg-popover no-scrollbar text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 ring-foreground/10 relative isolate flex max-h-72 w-(--brn-select-width) min-w-36 flex-col overflow-x-hidden overflow-y-auto rounded-md shadow-md ring-1 duration-100',
);
}
}
@Directive({
selector: '[hlmSelectGroup],hlm-select-group',
hostDirectives: [{ directive: BrnSelectGroup }],
host: {
'data-slot': 'select-group',
},
})
export class HlmSelectGroup {
constructor() {
classes(() => 'scroll-my-1 p-1');
}
}
@Component({
selector: 'hlm-select-item',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [{ directive: BrnSelectItem, inputs: ['id', 'disabled', 'value'] }],
host: {
'data-slot': 'select-item',
},
template: `
<ng-content />
@if (_active()) {
<ng-icon name="lucideCheck" class="absolute right-2 flex items-center justify-center" aria-hidden="true" />
}
`,
})
export class HlmSelectItem {
private readonly _brnSelectItem = inject(BrnSelectItem);
protected readonly _active = this._brnSelectItem.active;
constructor() {
classes(
() =>
"data-highlighted:bg-accent data-highlighted::text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0 [&_ng-icon:not([class*='text-'])]:text-base *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
);
}
}
@Directive({
selector: '[hlmSelectLabel],hlm-select-label',
hostDirectives: [{ directive: BrnSelectLabel, inputs: ['id'] }],
host: {
'data-slot': 'select-label',
},
})
export class HlmSelectLabel {
constructor() {
classes(() => 'text-muted-foreground block px-2 py-1.5 text-xs');
}
}
@Directive({
selector: '[hlmSelectMultiple],hlm-select-multiple',
providers: [
provideBrnPopoverConfig({
align: 'start',
sideOffset: 6,
}),
provideBrnDialogDefaultOptions({
autoFocus: 'first-heading',
}),
],
hostDirectives: [
{
directive: BrnSelectMultiple,
inputs: ['disabled', 'value', 'isItemEqualToValue', 'itemToString'],
outputs: ['valueChange'],
},
{
directive: BrnPopover,
inputs: [
'align',
'autoFocus',
'closeDelay',
'closeOnOutsidePointerEvents',
'sideOffset',
'state',
'offsetX',
'restoreFocus',
],
outputs: ['stateChanged', 'closed'],
},
],
host: {
'data-slot': 'select',
},
})
export class HlmSelectMultiple {
constructor() {
classes(() => 'block');
}
}
@Directive({
selector: '[hlmSelectPlaceholder],hlm-select-placeholder',
hostDirectives: [BrnSelectPlaceholder],
host: { 'data-slot': 'select-placeholder' },
})
export class HlmSelectPlaceholder {
constructor() {
classes(
() =>
"flex items-center gap-2 data-hidden:hidden [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0 [&_ng-icon:not([class*='text-'])]:text-base",
);
}
}
@Directive({
selector: '[hlmSelectPortal]',
hostDirectives: [{ directive: BrnPopoverContent, inputs: ['context', 'class'] }],
})
export class HlmSelectPortal {}
@Component({
selector: 'hlm-select-scroll-down',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronDown })],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [BrnSelectScrollDown],
template: `
<ng-icon name="lucideChevronDown" />
`,
})
export class HlmSelectScrollDown {
constructor() {
classes(
() =>
"bg-popover sticky bottom-0 z-10 flex w-full cursor-default items-center justify-center py-1 data-hidden:hidden [&_ng-icon:not([class*='text-'])]:text-base",
);
}
}
@Component({
selector: 'hlm-select-scroll-up',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronUp })],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [BrnSelectScrollUp],
template: `
<ng-icon name="lucideChevronUp" />
`,
})
export class HlmSelectScrollUp {
constructor() {
classes(
() =>
"bg-popover sticky top-0 z-10 flex w-full cursor-default items-center justify-center py-1 data-hidden:hidden [&_ng-icon:not([class*='text-'])]:text-base",
);
}
}
@Directive({
selector: '[hlmSelectSeparator],hlm-select-separator',
hostDirectives: [{ directive: BrnSelectSeparator, inputs: ['orientation'] }],
host: {
'data-slot': 'select-separator',
},
})
export class HlmSelectSeparator {
constructor() {
classes(() => 'bg-border pointer-events-none -mx-1 my-1 h-px shrink-0');
}
}
@Component({
selector: 'hlm-select-trigger',
imports: [NgIcon, BrnSelectTrigger, BrnFieldControlDescribedBy],
providers: [provideIcons({ lucideChevronDown })],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [BrnSelectTriggerWrapper],
template: `
<button
brnSelectTrigger
brnFieldControlDescribedBy
[id]="buttonId()"
[class]="_computedClass()"
[attr.data-size]="size()"
data-slot="select-trigger"
>
<ng-content />
<ng-icon name="lucideChevronDown" class="text-muted-foreground pointer-events-none text-base" />
</button>
`,
})
export class HlmSelectTrigger {
private static _id = 0;
public readonly userClass = input<ClassValue>('', { alias: 'class' });
protected readonly _computedClass = computed(() =>
hlm(
"border-input data-placeholder:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 focus-visible:border-ring focus-visible:ring-ring/50 flex w-full items-center justify-between gap-1.5 rounded-md border bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0 [&_ng-icon:not([class*='text-'])]:text-base",
'data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 data-[matches-spartan-invalid=true]:ring-3',
this.userClass(),
),
);
public readonly buttonId = input<string>(`hlm-select-trigger-${HlmSelectTrigger._id++}`);
public readonly size = input<'default' | 'sm'>('default');
}
@Directive({ selector: '[hlmSelectValueTemplate]', hostDirectives: [BrnSelectValueTemplate] })
export class HlmSelectValueTemplate {}
@Directive({
selector: '[hlmSelectValue],hlm-select-value',
hostDirectives: [{ directive: BrnSelectValue, inputs: ['placeholder'] }],
host: { '[attr.data-slot]': '!_hidden() ? "select-value" : null' },
})
export class HlmSelectValue {
private readonly _brnSelectValue = inject(BrnSelectValue);
protected readonly _hidden = this._brnSelectValue.hidden;
constructor() {
classes(() => 'data-hidden:hidden');
}
}
@Directive({ selector: '[hlmSelectValuesContent],hlm-select-values-content' })
export class HlmSelectValuesContent {
constructor() {
classes(() => 'flex gap-1');
}
}
@Directive({ selector: '[hlmSelectValues]', hostDirectives: [BrnSelectValues] })
export class HlmSelectValues {}
@Directive({
selector: '[hlmSelect],hlm-select',
providers: [
provideBrnPopoverConfig({
align: 'start',
sideOffset: 6,
}),
provideBrnDialogDefaultOptions({
autoFocus: 'first-heading',
}),
],
hostDirectives: [
{
directive: BrnSelect,
inputs: ['disabled', 'value', 'isItemEqualToValue', 'itemToString'],
outputs: ['valueChange'],
},
{
directive: BrnPopover,
inputs: [
'align',
'autoFocus',
'closeDelay',
'closeOnOutsidePointerEvents',
'sideOffset',
'state',
'offsetX',
'restoreFocus',
],
outputs: ['stateChanged', 'closed'],
},
],
host: {
'data-slot': 'select',
},
})
export class HlmSelect {
constructor() {
classes(() => 'block');
}
}
export const HlmSelectImports = [
HlmSelect,
HlmSelectContent,
HlmSelectGroup,
HlmSelectItem,
HlmSelectLabel,
HlmSelectMultiple,
HlmSelectPlaceholder,
HlmSelectPortal,
HlmSelectScrollDown,
HlmSelectScrollUp,
HlmSelectSeparator,
HlmSelectTrigger,
HlmSelectValue,
HlmSelectValues,
HlmSelectValuesContent,
HlmSelectValueTemplate,
] as const;Usage
import { HlmSelectImports } from '@spartan-ng/helm/select';<hlm-select>
<hlm-select-trigger>
<hlm-select-value placeholder="Select a fruit" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (item of items; track item.value) {
<hlm-select-item [value]="item.value">{{ item.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>@import '@angular/cdk/overlay-prebuilt.css';Examples
Groups
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-group-preview',
imports: [HlmSelectImports],
template: `
<hlm-select>
<hlm-select-trigger class="w-56">
<hlm-select-value placeholder="Select a fruit" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (fruit of fruits; track fruit.value) {
<hlm-select-item [value]="fruit">{{ fruit.label }}</hlm-select-item>
}
</hlm-select-group>
<hlm-select-separator />
<hlm-select-group>
<hlm-select-label>Vegetables</hlm-select-label>
@for (vegetable of vegetables; track vegetable.value) {
<hlm-select-item [value]="vegetable">{{ vegetable.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class SelectGroupPreview {
public readonly fruits = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
public readonly vegetables = [
{ label: 'Carrot', value: 'carrot' },
{ label: 'Broccoli', value: 'broccoli' },
{ label: 'Spinach', value: 'spinach' },
];
}Multiple
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-multiple-preview',
imports: [HlmSelectImports],
template: `
<hlm-select-multiple>
<hlm-select-trigger class="w-56">
<hlm-select-placeholder>Select fruits</hlm-select-placeholder>
<ng-template hlmSelectValues let-values>
<hlm-select-values-content>
{{ values[0].label }}
@if (values.length > 1) {
(+{{ values.length - 1 }} more)
}
</hlm-select-values-content>
</ng-template>
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (item of items; track item.value) {
<hlm-select-item [value]="item">{{ item.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select-multiple>
`,
})
export class SelectMultiplePreview {
public readonly items = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
}Scrollable
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-scrollable-preview',
imports: [HlmSelectImports],
template: `
<hlm-select [itemToString]="itemToString">
<hlm-select-trigger class="w-80">
<hlm-select-value placeholder="Select a time zone" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal showScroll class="max-h-96">
@for (timezone of timezones; track $index) {
<hlm-select-group>
<hlm-select-label>{{ timezone.group }}</hlm-select-label>
@for (option of timezone.options; track $index) {
<hlm-select-item [value]="option.value">{{ option.label }}</hlm-select-item>
}
</hlm-select-group>
}
</hlm-select-content>
</hlm-select>
`,
})
export class SelectScrollablePreview {
public readonly timezones = [
{
group: 'North America',
options: [
{ label: 'Eastern Standard Time', value: 'est' },
{ label: 'Central Standard Time', value: 'cst' },
{ label: 'Mountain Standard Time', value: 'mst' },
{ label: 'Pacific Standard Time', value: 'pst' },
{ label: 'Alaska Standard Time', value: 'akst' },
{ label: 'Hawaii Standard Time', value: 'hst' },
],
},
{
group: 'Europe & Africa',
options: [
{ label: 'Greenwich Mean Time', value: 'gmt' },
{ label: 'Central European Time', value: 'cet' },
{ label: 'Eastern European Time', value: 'eet' },
{ label: 'Western European Summer Time', value: 'west' },
{ label: 'Central Africa Time', value: 'cat' },
{ label: 'East Africa Time', value: 'eat' },
],
},
{
group: 'Asia',
options: [
{ label: 'Moscow Time', value: 'msk' },
{ label: 'India Standard Time', value: 'ist' },
{ label: 'China Standard Time', value: 'cst_china' },
{ label: 'Japan Standard Time', value: 'jst' },
{ label: 'Korea Standard Time', value: 'kst' },
{ label: 'Indonesia Central Standard Time', value: 'ist_indonesia' },
],
},
{
group: 'Australia & Pacific',
options: [
{ label: 'Australian Western Standard Time', value: 'awst' },
{ label: 'Australian Central Standard Time', value: 'acst' },
{ label: 'Australian Eastern Standard Time', value: 'aest' },
{ label: 'New Zealand Standard Time', value: 'nzst' },
{ label: 'Fiji Time', value: 'fjt' },
],
},
{
group: 'South America',
options: [
{ label: 'Argentina Time', value: 'art' },
{ label: 'Bolivia Time', value: 'bot' },
{ label: 'Brasilia Time', value: 'brt' },
{ label: 'Chile Standard Time', value: 'clt' },
],
},
];
public readonly itemToString = (value: string) =>
this.timezones.flatMap((group) => group.options).find((option) => option.value === value)?.label || '';
}Disabled
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-disabled-preview',
imports: [HlmSelectImports],
template: `
<hlm-select disabled>
<hlm-select-trigger class="w-56">
<hlm-select-value placeholder="Select a fruit" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (item of items; track item.value) {
<hlm-select-item [value]="item.value">{{ item.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class SelectDisabledPreview {
public readonly items = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
}Object values
import { Component } from '@angular/core';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-object-preview',
imports: [HlmSelectImports],
template: `
<hlm-select>
<hlm-select-trigger class="w-72">
<hlm-select-placeholder>Select a shipping method</hlm-select-placeholder>
<ng-template hlmSelectValueTemplate let-value>
<div class="flex items-baseline gap-0.5">
<span>{{ value.name }}</span>
<span class="text-muted-foreground text-xs">({{ value.price }})</span>
</div>
</ng-template>
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
@for (method of shippingMethods; track method.id) {
<hlm-select-item [value]="method">
<div class="flex flex-col gap-0.5">
<div class="flex items-baseline gap-0.5">
<span>{{ method.name }}</span>
<span class="text-muted-foreground text-xs">({{ method.price }})</span>
</div>
<span class="text-muted-foreground text-xs">{{ method.duration }}</span>
</div>
</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class SelectObjectPreview {
public readonly shippingMethods = [
{
id: 'standard',
name: 'Standard',
duration: 'Delivers in 4-6 business days',
price: '$4.99',
},
{
id: 'express',
name: 'Express',
duration: 'Delivers in 2-3 business days',
price: '$9.99',
},
{
id: 'overnight',
name: 'Overnight',
duration: 'Delivers next business day',
price: '$19.99',
},
];
}Placeholder
Use hlm-select-placeholder to display a custom placeholder when no value is selected. If you only display a text as placeholder, you can also use the placeholder input on hlm-select-value .
import { Component } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideCitrus } from '@ng-icons/lucide';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-placeholder-preview',
imports: [HlmSelectImports, NgIcon],
providers: [provideIcons({ lucideCitrus })],
template: `
<hlm-select>
<hlm-select-trigger class="w-56">
<hlm-select-placeholder>
<ng-icon name="lucideCitrus" />
Select a fruit
</hlm-select-placeholder>
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (fruit of fruits; track fruit.value) {
<hlm-select-item [value]="fruit">{{ fruit.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class SelectPlaceholderPreview {
public readonly fruits = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
}Form
import { Component, inject } from '@angular/core';
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-select-form-preview',
imports: [HlmFieldImports, HlmSelectImports, HlmButtonImports, ReactiveFormsModule],
host: {
class: 'w-full max-w-xs',
},
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<hlm-field-group>
<hlm-field>
<label hlmFieldLabel for="fruit">Fruit</label>
<hlm-select formControlName="fruit" [itemToString]="itemToString">
<hlm-select-trigger buttonId="fruit" class="w-56">
<hlm-select-value placeholder="Select a fruit" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-label>Fruits</hlm-select-label>
@for (item of items; track item.value) {
<hlm-select-item [value]="item.value">{{ item.label }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</hlm-field>
<hlm-field orientation="horizontal">
<button type="submit" hlmBtn>Submit</button>
</hlm-field>
</hlm-field-group>
</form>
`,
})
export class SelectFormPreview {
private readonly _formBuilder = inject(FormBuilder);
public form = this._formBuilder.group({
fruit: new FormControl<string | null>(null, Validators.required),
});
public readonly items = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Blueberry', value: 'blueberry' },
{ label: 'Grapes', value: 'grapes' },
{ label: 'Pineapple', value: 'pineapple' },
];
public readonly itemToString = (value: string) => this.items.find((item) => item.value === value)?.label || '';
public submit() {
console.log(this.form.value);
}
}Brain API
BrnSelectContent
Selector: [brnSelectContent]
BrnSelectGroup
Selector: [brnSelectGroup]
BrnSelectItem
Selector: [brnSelectItem]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | `brn-select-item-${++BrnSelectItem._id}` | A unique id for the item |
| value* (required) | T | - | The value this item represents. |
| disabled | boolean | false | - |
BrnSelectLabel
Selector: [brnSelectLabel]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | `brn-select-label-${++BrnSelectLabel._id}` | - |
BrnSelectList
Selector: [brnSelectList]
BrnSelectMultiple
Selector: [brnSelectMultiple]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean | false | Whether the combobox is disabled |
| isItemEqualToValue | SelectItemEqualToValue<T> | this._config.isItemEqualToValue | A function to compare an item with the selected value. |
| itemToString | SelectItemToString<T> | undefined | this._config.itemToString | A function to convert an item to a string for display. |
| value | T[] | null | null | The selected value of the select. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| valueChange | T[] | null | null | The selected value of the select. |
BrnSelectPlaceholder
Selector: [brnSelectPlaceholder]
BrnSelectScrollDown
Selector: [brnSelectScrollDown]
BrnSelectScrollUp
Selector: [brnSelectScrollUp]
BrnSelectSeparator
Selector: [brnSelectSeparator]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| orientation | 'horizontal' | 'vertical' | horizontal | - |
BrnSelectTriggerWrapper
Selector: [brnSelectTriggerWrapper]
BrnSelectTrigger
Selector: button[brnSelectTrigger]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | `brn-select-trigger-${++BrnSelectTrigger._id}` | - |
BrnSelectValueTemplate
Selector: [brnSelectValueTemplate]
BrnSelectValue
Selector: [brnSelectValue]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| placeholder | string | - | - |
BrnSelectValues
Selector: [brnSelectValues]
BrnSelect
Selector: [brnSelect]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean | false | Whether the select is disabled |
| isItemEqualToValue | SelectItemEqualToValue<T> | this._config.isItemEqualToValue | A function to compare an item with the selected value. |
| itemToString | SelectItemToString<T> | undefined | this._config.itemToString | A function to convert an item to a string for display. |
| value | T | null | null | The selected value of the select. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| valueChange | T | null | null | The selected value of the select. |
Helm API
HlmSelectContent
Selector: hlm-select-content
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| showScroll | boolean | false | - |
HlmSelectGroup
Selector: [hlmSelectGroup],hlm-select-group
HlmSelectItem
Selector: hlm-select-item
HlmSelectLabel
Selector: [hlmSelectLabel],hlm-select-label
HlmSelectMultiple
Selector: [hlmSelectMultiple],hlm-select-multiple
HlmSelectPlaceholder
Selector: [hlmSelectPlaceholder],hlm-select-placeholder
HlmSelectPortal
Selector: [hlmSelectPortal]
HlmSelectScrollDown
Selector: hlm-select-scroll-down
HlmSelectScrollUp
Selector: hlm-select-scroll-up
HlmSelectSeparator
Selector: [hlmSelectSeparator],hlm-select-separator
HlmSelectTrigger
Selector: hlm-select-trigger
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| class | ClassValue | - | - |
| buttonId | string | `hlm-select-trigger-${HlmSelectTrigger._id++}` | - |
| size | 'default' | 'sm' | default | - |
HlmSelectValueTemplate
Selector: [hlmSelectValueTemplate]
HlmSelectValue
Selector: [hlmSelectValue],hlm-select-value
HlmSelectValuesContent
Selector: [hlmSelectValuesContent],hlm-select-values-content
HlmSelectValues
Selector: [hlmSelectValues]
HlmSelect
Selector: [hlmSelect],hlm-select
On This Page