- 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
Dropdown
Displays a menu to the user — such as a set of actions or functions — triggered by a button.
import { Component } from '@angular/core';
import { provideIcons } from '@ng-icons/core';
import {
lucideCircleHelp,
lucideCirclePlus,
lucideCircleUser,
lucideCode,
lucideCog,
lucideGithub,
lucideKeyboard,
lucideLayers,
lucideLogOut,
lucideMail,
lucideMessageSquare,
lucidePlus,
lucideSmile,
lucideUser,
} from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-preview',
imports: [HlmDropdownMenuImports, HlmButtonImports],
providers: [
provideIcons({
lucideUser,
lucideLayers,
lucideCog,
lucideKeyboard,
lucideCircleUser,
lucideSmile,
lucidePlus,
lucideGithub,
lucideCircleHelp,
lucideCode,
lucideLogOut,
lucideMail,
lucideMessageSquare,
lucideCirclePlus,
}),
],
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
<span>Profile</span>
<hlm-dropdown-menu-shortcut>⇧⌘P</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
<span>Billing</span>
<hlm-dropdown-menu-shortcut>⌘B</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
<span>Settings</span>
<hlm-dropdown-menu-shortcut>⌘S</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem>
<span>Keyboard shortcuts</span>
<hlm-dropdown-menu-shortcut>⌘K</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
<span>Team</span>
<hlm-dropdown-menu-shortcut>⌘B</hlm-dropdown-menu-shortcut>
</button>
<button hlmDropdownMenuItem side="right" align="start" [hlmDropdownMenuTrigger]="invite">
<span>Invite Users</span>
<hlm-dropdown-menu-item-sub-indicator />
</button>
<button hlmDropdownMenuItem>
<span>New Team</span>
<hlm-dropdown-menu-shortcut>⌘+T</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
<span>GitHub</span>
</button>
<button hlmDropdownMenuItem>
<span>Support</span>
</button>
<button hlmDropdownMenuItem disabled>
<span>API</span>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>
Log out
<hlm-dropdown-menu-shortcut>⇧⌘Q</hlm-dropdown-menu-shortcut>
</button>
</hlm-dropdown-menu>
</ng-template>
<ng-template #invite>
<hlm-dropdown-menu-sub>
<button hlmDropdownMenuItem>Email</button>
<button hlmDropdownMenuItem>Message</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem>More...</button>
</hlm-dropdown-menu-sub>
</ng-template>
`,
})
export class DropdownPreview {}About
Dropdown Menu is built with the help of Menu from Material CDK .
Installation
ng g @spartan-ng/cli:ui dropdown-menunx g @spartan-ng/cli:ui dropdown-menuimport { 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 { CdkMenu, CdkMenuGroup, CdkMenuItem, CdkMenuItemCheckbox, CdkMenuItemRadio, CdkMenuTrigger } from '@angular/cdk/menu';
import { ChangeDetectionStrategy, Component, Directive, HOST_TAG_NAME, InjectionToken, booleanAttribute, computed, effect, inject, input, numberAttribute, signal, type ValueProvider } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { createMenuPosition, type MenuAlign, type MenuSide } from '@spartan-ng/brain/core';
import { lucideCheck, lucideChevronRight, lucideCircle } from '@ng-icons/lucide';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
@Component({
selector: 'hlm-dropdown-menu-checkbox-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCheck })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon class="text-base" name="lucideCheck" />
`,
})
export class HlmDropdownMenuCheckboxIndicator {
constructor() {
classes(
() =>
'pointer-events-none absolute left-2 flex size-3.5 items-center justify-center opacity-0 group-data-[checked]:opacity-100',
);
}
}
@Directive({
selector: '[hlmDropdownMenuCheckbox]',
hostDirectives: [
{
directive: CdkMenuItemCheckbox,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-checkbox-item',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-checked]': 'checked() ? "" : null',
},
})
export class HlmDropdownMenuCheckbox {
private readonly _cdkMenuItem = inject(CdkMenuItemCheckbox);
public readonly checked = input<boolean, BooleanInput>(this._cdkMenuItem.checked, { transform: booleanAttribute });
public readonly disabled = input<boolean, BooleanInput>(this._cdkMenuItem.disabled, { transform: booleanAttribute });
constructor() {
classes(
() =>
'hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground group relative flex w-full cursor-default items-center rounded-sm py-1.5 pr-2 pl-8 text-sm transition-colors outline-none select-none has-[>hlm-dropdown-menu-checkbox-indicator:last-child]:ps-2 has-[>hlm-dropdown-menu-checkbox-indicator:last-child]:pe-8 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 has-[>hlm-dropdown-menu-checkbox-indicator:last-child]:[&>hlm-dropdown-menu-checkbox-indicator]:start-auto has-[>hlm-dropdown-menu-checkbox-indicator:last-child]:[&>hlm-dropdown-menu-checkbox-indicator]:end-2',
);
}
}
@Directive({
selector: '[hlmDropdownMenuGroup],hlm-dropdown-menu-group',
hostDirectives: [CdkMenuGroup],
host: {
'data-slot': 'dropdown-menu-group',
},
})
export class HlmDropdownMenuGroup {
constructor() {
classes(() => 'block');
}
}
@Component({
selector: 'hlm-dropdown-menu-item-sub-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideChevronRight" class="text-base" />
`,
})
export class HlmDropdownMenuItemSubIndicator {
constructor() {
classes(() => 'ms-auto size-4');
}
}
@Directive({
selector: '[hlmDropdownMenuItem]',
hostDirectives: [
{
directive: CdkMenuItem,
inputs: ['cdkMenuItemDisabled: disabled'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-item',
'[attr.disabled]': '_isButton && disabled() ? "" : null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-variant]': 'variant()',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuItem {
protected readonly _isButton = inject(HOST_TAG_NAME) === 'button';
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
public readonly variant = input<'default' | 'destructive'>('default');
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
constructor() {
classes(
() =>
"hover:bg-accent focus-visible:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[ng-icon]:!text-destructive [&_ng-icon:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_ng-icon]:pointer-events-none [&_ng-icon]:shrink-0 [&_svg:not([class*='text-'])]:text-base",
);
}
}
@Directive({
selector: '[hlmDropdownMenuLabel],hlm-dropdown-menu-label',
host: {
'data-slot': 'dropdown-menu-label',
'[attr.data-inset]': 'inset() ? "" : null',
},
})
export class HlmDropdownMenuLabel {
constructor() {
classes(() => 'block px-2 py-1.5 text-sm font-medium data-[inset]:pl-8');
}
public readonly inset = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
}
@Component({
selector: 'hlm-dropdown-menu-radio-indicator',
imports: [NgIcon],
providers: [provideIcons({ lucideCircle })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<ng-icon name="lucideCircle" class="text-[0.5rem] *:[svg]:fill-current" />
`,
})
export class HlmDropdownMenuRadioIndicator {
constructor() {
classes(
() =>
'pointer-events-none absolute left-2 flex size-3.5 items-center justify-center opacity-0 group-data-[checked]:opacity-100',
);
}
}
@Directive({
selector: '[hlmDropdownMenuRadio]',
hostDirectives: [
{
directive: CdkMenuItemRadio,
inputs: ['cdkMenuItemDisabled: disabled', 'cdkMenuItemChecked: checked'],
outputs: ['cdkMenuItemTriggered: triggered'],
},
],
host: {
'data-slot': 'dropdown-menu-radio-item',
'[attr.data-disabled]': 'disabled() ? "" : null',
'[attr.data-checked]': 'checked() ? "" : null',
},
})
export class HlmDropdownMenuRadio {
private readonly _cdkMenuItem = inject(CdkMenuItemRadio);
public readonly checked = input<boolean, BooleanInput>(this._cdkMenuItem.checked, { transform: booleanAttribute });
public readonly disabled = input<boolean, BooleanInput>(this._cdkMenuItem.disabled, { transform: booleanAttribute });
constructor() {
classes(
() =>
'hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground group relative flex w-full cursor-default items-center rounded-sm py-1.5 pr-2 pl-8 text-sm transition-colors outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
);
}
}
@Directive({
selector: '[hlmDropdownMenuSeparator],hlm-dropdown-menu-separator',
host: {
'data-slot': 'dropdown-menu-separator',
},
})
export class HlmDropdownMenuSeparator {
constructor() {
classes(() => 'bg-border -mx-1 my-1 block h-px');
}
}
@Directive({
selector: '[hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut',
host: {
'data-slot': 'dropdown-menu-shortcut',
},
})
export class HlmDropdownMenuShortcut {
constructor() {
classes(() => 'text-muted-foreground ml-auto text-xs tracking-widest');
}
}
@Directive({
selector: '[hlmDropdownMenuSub],hlm-dropdown-menu-sub',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu-sub',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
},
})
export class HlmDropdownMenuSub {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
constructor() {
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
classes(
() =>
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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 z-50 min-w-[8rem] origin-top overflow-hidden rounded-md border p-1 shadow-lg',
);
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export interface HlmDropdownMenuConfig {
align: MenuAlign;
side: MenuSide;
}
const defaultConfig: HlmDropdownMenuConfig = {
align: 'start',
side: 'bottom',
};
const HlmDropdownMenuConfigToken = new InjectionToken<HlmDropdownMenuConfig>('HlmDropdownMenuConfig');
export function provideHlmDropdownMenuConfig(config: Partial<HlmDropdownMenuConfig>): ValueProvider {
return { provide: HlmDropdownMenuConfigToken, useValue: { ...defaultConfig, ...config } };
}
export function injectHlmDropdownMenuConfig(): HlmDropdownMenuConfig {
return inject(HlmDropdownMenuConfigToken, { optional: true }) ?? defaultConfig;
}
@Directive({
selector: '[hlmDropdownMenuTrigger]',
hostDirectives: [
{
directive: CdkMenuTrigger,
inputs: ['cdkMenuTriggerFor: hlmDropdownMenuTrigger', 'cdkMenuTriggerData: hlmDropdownMenuTriggerData'],
outputs: ['cdkMenuOpened: hlmDropdownMenuOpened', 'cdkMenuClosed: hlmDropdownMenuClosed'],
},
],
host: {
'data-slot': 'dropdown-menu-trigger',
},
})
export class HlmDropdownMenuTrigger {
private readonly _cdkTrigger = inject(CdkMenuTrigger, { host: true });
private readonly _config = injectHlmDropdownMenuConfig();
public readonly align = input<MenuAlign>(this._config.align);
public readonly side = input<MenuSide>(this._config.side);
private readonly _menuPosition = computed(() => createMenuPosition(this.align(), this.side()));
constructor() {
// once the trigger opens we wait until the next tick and then grab the last position
// used to position the menu. we store this in our trigger which the brnMenu directive has
// access to through DI
this._cdkTrigger.opened.pipe(takeUntilDestroyed()).subscribe(() =>
setTimeout(
() =>
// eslint-disable-next-line
((this._cdkTrigger as any)._spartanLastPosition = // eslint-disable-next-line
(this._cdkTrigger as any).overlayRef._positionStrategy._lastPosition),
),
);
effect(() => {
this._cdkTrigger.menuPosition = this._menuPosition();
});
}
}
@Directive({
selector: '[hlmDropdownMenu],hlm-dropdown-menu',
hostDirectives: [CdkMenu],
host: {
'data-slot': 'dropdown-menu',
'[attr.data-state]': '_state()',
'[attr.data-side]': '_side()',
'[style.--side-offset]': 'sideOffset()',
},
})
export class HlmDropdownMenu {
private readonly _host = inject(CdkMenu);
protected readonly _state = signal('open');
protected readonly _side = signal('top');
public readonly sideOffset = input<number, NumberInput>(1, { transform: numberAttribute });
constructor() {
classes(
() =>
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=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 z-50 my-[--spacing(var(--side-offset))] min-w-[8rem] origin-top overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md',
);
this.setSideWithDarkMagic();
// this is a best effort, but does not seem to work currently
// TODO: figure out a way for us to know the host is about to be closed. might not be possible with CDK
this._host.closed.pipe(takeUntilDestroyed()).subscribe(() => this._state.set('closed'));
}
private setSideWithDarkMagic() {
/**
* This is an ugly workaround to at least figure out the correct side of where a submenu
* will appear and set the attribute to the host accordingly
*
* First of all we take advantage of the menu stack not being aware of the root
* object immediately after it is added. This code executes before the root element is added,
* which means the stack is still empty and the peek method returns undefined.
*/
const isRoot = this._host.menuStack.peek() === undefined;
setTimeout(() => {
// our menu trigger directive leaves the last position used for use immediately after opening
// we can access it here and determine the correct side.
// eslint-disable-next-line
const ps = (this._host as any)._parentTrigger._spartanLastPosition;
if (!ps) {
// if we have no last position we default to the most likely option
// I hate that we have to do this and hope we can revisit soon and improve
this._side.set(isRoot ? 'top' : 'left');
return;
}
const side = isRoot ? ps.originY : ps.originX === 'end' ? 'right' : 'left';
this._side.set(side);
});
}
}
export const HlmDropdownMenuImports = [
HlmDropdownMenu,
HlmDropdownMenuCheckbox,
HlmDropdownMenuCheckboxIndicator,
HlmDropdownMenuGroup,
HlmDropdownMenuItem,
HlmDropdownMenuItemSubIndicator,
HlmDropdownMenuLabel,
HlmDropdownMenuRadio,
HlmDropdownMenuRadioIndicator,
HlmDropdownMenuSeparator,
HlmDropdownMenuShortcut,
HlmDropdownMenuSub,
HlmDropdownMenuTrigger,
] as const;Usage
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';<button [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu>
<hlm-dropdown-menu-label>My Account</hlm-dropdown-menu-label>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-group>
<button hlmDropdownMenuItem>
Profile
<hlm-dropdown-menu-shortcut>⇧⌘P</hlm-dropdown-menu-shortcut>
</button>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem [hlmDropdownMenuTrigger]="invite">
Invite Users
<hlm-dropdown-menu-item-sub-indicator />
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>Examples
Checkboxes
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-menu-checkboxes',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Status Bar</span>
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
<hlm-dropdown-menu-checkbox-indicator />
<span>Activity Bar</span>
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Panel</span>
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownMenuCheckboxes {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
}Radio Group
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { MenuSide } from '@spartan-ng/brain/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
@Component({
selector: 'spartan-dropdown-menu-radio-group',
imports: [HlmDropdownMenuImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<button hlmBtn variant="outline" [hlmDropdownMenuTrigger]="menu">Open</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
<hlm-dropdown-menu-separator />
@let p = position();
<button hlmDropdownMenuRadio [checked]="p === 'top'" (triggered)="position.set('top')">
<hlm-dropdown-menu-radio-indicator />
<span>Top</span>
</button>
<button hlmDropdownMenuRadio [checked]="p === 'bottom'" (triggered)="position.set('bottom')">
<hlm-dropdown-menu-radio-indicator />
<span>Bottom</span>
</button>
<button hlmDropdownMenuRadio [checked]="p === 'right'" (triggered)="position.set('right')">
<hlm-dropdown-menu-radio-indicator />
<span>Right</span>
</button>
</hlm-dropdown-menu-group>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownMenuRadioGroup {
public readonly position = signal<MenuSide>('bottom');
}Stateful
import { Component, signal } from '@angular/core';
import { provideIcons } from '@ng-icons/core';
import { lucideUndo2 } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
import { HlmIconImports } from '@spartan-ng/helm/icon';
@Component({
selector: 'spartan-dropdown-with-state',
imports: [HlmDropdownMenuImports, HlmButtonImports, HlmIconImports],
providers: [provideIcons({ lucideUndo2 })],
template: `
<div class="flex w-full items-center justify-center pt-[20%]">
<button hlmBtn variant="outline" align="center" [hlmDropdownMenuTrigger]="menu">Open</button>
</div>
<ng-template #menu>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Status Bar</span>
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
<hlm-dropdown-menu-checkbox-indicator />
<span>Activity Bar</span>
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Panel</span>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
<hlm-dropdown-menu-group>
@for (size of panelPositions; track size) {
<button hlmDropdownMenuRadio [checked]="size === selectedPosition" (triggered)="selectedPosition = size">
<hlm-dropdown-menu-radio-indicator />
<span>{{ size }}</span>
</button>
}
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem (triggered)="reset()">
<ng-icon hlm name="lucideUndo2" size="sm" />
Reset
</button>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownWithStatePreview {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
public panelPositions = ['Top', 'Bottom', 'Right', 'Left'] as const;
public selectedPosition: (typeof this.panelPositions)[number] | undefined = 'Bottom';
reset() {
this.statusBar.set(false);
this.panel.set(false);
this.activityBar.set(false);
this.selectedPosition = 'Bottom';
}
}Passing context to menu
import { Component, signal } from '@angular/core';
import { provideIcons } from '@ng-icons/core';
import { lucideUndo2 } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
import { HlmIconImports } from '@spartan-ng/helm/icon';
@Component({
selector: 'spartan-dropdown-with-context',
imports: [HlmDropdownMenuImports, HlmButtonImports, HlmIconImports],
providers: [provideIcons({ lucideUndo2 })],
template: `
<div class="flex w-full items-center justify-center pt-[20%]">
<button
hlmBtn
variant="outline"
align="center"
[hlmDropdownMenuTrigger]="menu"
[hlmDropdownMenuTriggerData]="{ $implicit: { data: 'Context Window Full' } }"
>
Open
</button>
</div>
<ng-template #menu let-ctx>
<hlm-dropdown-menu class="w-56">
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Context</hlm-dropdown-menu-label>
<button hlmDropdownMenuItem inset>{{ ctx.data }}</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-group>
<hlm-dropdown-menu-label>Appearance</hlm-dropdown-menu-label>
<button hlmDropdownMenuCheckbox [checked]="statusBar()" (triggered)="statusBar.set(!statusBar())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Status Bar</span>
</button>
<button
hlmDropdownMenuCheckbox
disabled
[checked]="activityBar()"
(triggered)="activityBar.set(!activityBar())"
>
<hlm-dropdown-menu-checkbox-indicator />
<span>Activity Bar</span>
</button>
<button hlmDropdownMenuCheckbox [checked]="panel()" (triggered)="panel.set(!panel())">
<hlm-dropdown-menu-checkbox-indicator />
<span>Panel</span>
</button>
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<hlm-dropdown-menu-label>Panel Position</hlm-dropdown-menu-label>
<hlm-dropdown-menu-group>
@for (size of panelPositions; track size) {
<button hlmDropdownMenuRadio [checked]="size === selectedPosition" (triggered)="selectedPosition = size">
<hlm-dropdown-menu-radio-indicator />
<span>{{ size }}</span>
</button>
}
</hlm-dropdown-menu-group>
<hlm-dropdown-menu-separator />
<button hlmDropdownMenuItem (triggered)="reset()">
<ng-icon hlm name="lucideUndo2" size="sm" />
Reset
</button>
</hlm-dropdown-menu>
</ng-template>
`,
})
export class DropdownWithContextPreview {
public readonly statusBar = signal(true);
public readonly activityBar = signal(false);
public readonly panel = signal(false);
public panelPositions = ['Top', 'Bottom', 'Right', 'Left'] as const;
public selectedPosition: (typeof this.panelPositions)[number] | undefined = 'Bottom';
reset() {
this.statusBar.set(false);
this.panel.set(false);
this.activityBar.set(false);
this.selectedPosition = 'Bottom';
}
}Helm API
HlmDropdownMenuCheckboxIndicator
Selector: hlm-dropdown-menu-checkbox-indicator
HlmDropdownMenuCheckbox
Selector: [hlmDropdownMenuCheckbox]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| checked | boolean | this._cdkMenuItem.checked | - |
| disabled | boolean | this._cdkMenuItem.disabled | - |
HlmDropdownMenuGroup
Selector: [hlmDropdownMenuGroup],hlm-dropdown-menu-group
HlmDropdownMenuItemSubIndicator
Selector: hlm-dropdown-menu-item-sub-indicator
HlmDropdownMenuItem
Selector: [hlmDropdownMenuItem]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean | false | - |
| variant | 'default' | 'destructive' | default | - |
| inset | boolean | false | - |
HlmDropdownMenuLabel
Selector: [hlmDropdownMenuLabel],hlm-dropdown-menu-label
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| inset | boolean | false | - |
HlmDropdownMenuRadioIndicator
Selector: hlm-dropdown-menu-radio-indicator
HlmDropdownMenuRadio
Selector: [hlmDropdownMenuRadio]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| checked | boolean | this._cdkMenuItem.checked | - |
| disabled | boolean | this._cdkMenuItem.disabled | - |
HlmDropdownMenuSeparator
Selector: [hlmDropdownMenuSeparator],hlm-dropdown-menu-separator
HlmDropdownMenuShortcut
Selector: [hlmDropdownMenuShortcut],hlm-dropdown-menu-shortcut
HlmDropdownMenuSub
Selector: [hlmDropdownMenuSub],hlm-dropdown-menu-sub
HlmDropdownMenuTrigger
Selector: [hlmDropdownMenuTrigger]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| align | MenuAlign | this._config.align | - |
| side | MenuSide | this._config.side | - |
HlmDropdownMenu
Selector: [hlmDropdownMenu],hlm-dropdown-menu
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| sideOffset | number | 1 | - |
On This Page