- 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
Calendar
A date field component that allows users to enter and edit date.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
import { Component } from '@angular/core';
import { HlmCalendarImports } from '@spartan-ng/helm/calendar';
@Component({
selector: 'spartan-calendar-preview',
imports: [HlmCalendarImports],
template: `
<hlm-calendar [(date)]="selectedDate" [min]="minDate" [max]="maxDate" />
`,
})
export class CalendarPreview {
/** The selected date */
public selectedDate = new Date();
/** The minimum date */
public minDate = new Date(2023, 0, 1);
/** The maximum date */
public maxDate = new Date(2030, 11, 31);
}
export const i18nRuntimeChange = `
import { injectBrnCalendarI18n } from '@spartan-ng/brain/calendar';
@Component({...})
export class CalendarPage {
private readonly _i18n = injectBrnCalendarI18n();
switchToFrench() {
this._i18n.use({
...,
labelNext: () => 'Mois suivant',
labelPrevious: () => 'Mois précédent',
...
});
}
}
`;
export const i18nProviders = `
import { bootstrapApplication } from '@angular/platform-browser';
import { provideBrnCalendarI18n } from '@spartan-ng/brain/calendar';
bootstrapApplication(App, {
providers: [
provideBrnCalendarI18n({
formatWeekdayName: (i) => ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'][i],
formatHeader: (m, y) =>
new Date(y, m).toLocaleDateString('de-DE', {
month: 'long',
year: 'numeric',
}),
labelPrevious: () => 'Vorheriger Monat',
labelNext: () => 'Nächster Monat',
labelWeekday: (i) => ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'][i],
firstDayOfWeek: () => 1,
}),
],
});
`;Installation
ng g @spartan-ng/cli:ui calendarnx g @spartan-ng/cli:ui calendarimport { 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, { BooleanInput, NumberInput } from '@angular/cdk/coercion';
import type, { ClassValue } from 'clsx';
import { BrnCalendar, BrnCalendarImports, BrnCalendarMulti, BrnCalendarRange, injectBrnCalendarI18n, type Weekday } from '@spartan-ng/brain/calendar';
import { ChangeDetectionStrategy, Component, booleanAttribute, computed, input, model, numberAttribute, viewChild } from '@angular/core';
import { HlmIcon } from '@spartan-ng/helm/icon';
import { HlmSelectImports } from '@spartan-ng/helm/select';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { NgTemplateOutlet } from '@angular/common';
import { buttonVariants } from '@spartan-ng/helm/button';
import { hlm } from '@spartan-ng/helm/utils';
import { injectDateAdapter } from '@spartan-ng/brain/date-time';
import { lucideChevronLeft, lucideChevronRight } from '@ng-icons/lucide';
@Component({
selector: 'hlm-calendar-multi',
imports: [BrnCalendarImports, NgIcon, HlmIcon, NgTemplateOutlet, HlmSelectImports],
viewProviders: [provideIcons({ lucideChevronLeft, lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div
brnCalendarMulti
[min]="min()"
[max]="max()"
[minSelection]="minSelection()"
[maxSelection]="maxSelection()"
[disabled]="disabled()"
[(date)]="date"
[dateDisabled]="dateDisabled()"
[weekStartsOn]="weekStartsOn()"
[defaultFocusedDate]="defaultFocusedDate()"
[class]="_computedCalenderClass()"
>
<div class="inline-flex flex-col space-y-4">
<!-- Header -->
<div class="space-y-4">
<div class="relative flex items-center justify-center pt-1">
<div class="flex w-full items-center justify-center gap-1.5">
<ng-template #month>
<hlm-select brnCalendarMonthSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (month of _i18n.config().months(); track month) {
<hlm-select-item [value]="month">{{ month }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
<ng-template #year>
<hlm-select brnCalendarYearSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (year of _i18n.config().years(); track year) {
<hlm-select-item [value]="year">{{ year }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
@let heading = _heading();
@switch (captionLayout()) {
@case ('dropdown') {
<ng-container [ngTemplateOutlet]="month" />
<ng-container [ngTemplateOutlet]="year" />
}
@case ('dropdown-months') {
<ng-container [ngTemplateOutlet]="month" />
<div brnCalendarHeader class="text-sm font-medium">{{ heading.year }}</div>
}
@case ('dropdown-years') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.month }}</div>
<ng-container [ngTemplateOutlet]="year" />
}
@case ('label') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.header }}</div>
}
}
</div>
<div class="flex items-center space-x-1">
<button
brnCalendarPreviousButton
class="ring-offset-background focus-visible:ring-ring border-input hover:bg-accent hover:text-accent-foreground absolute left-1 inline-flex h-7 w-7 items-center justify-center rounded-md border bg-transparent p-0 text-sm font-medium whitespace-nowrap opacity-50 transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronLeft" size="sm" />
</button>
<button
brnCalendarNextButton
class="ring-offset-background focus-visible:ring-ring border-input hover:bg-accent hover:text-accent-foreground absolute right-1 inline-flex h-7 w-7 items-center justify-center rounded-md border bg-transparent p-0 text-sm font-medium whitespace-nowrap opacity-50 transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronRight" size="sm" />
</button>
</div>
</div>
</div>
<table class="w-full border-collapse space-y-1" brnCalendarGrid>
<thead>
<tr class="flex">
<th
*brnCalendarWeekday="let weekday"
scope="col"
class="text-muted-foreground w-8 rounded-md text-[0.8rem] font-normal"
[attr.aria-label]="_i18n.config().labelWeekday(weekday)"
>
{{ _i18n.config().formatWeekdayName(weekday) }}
</th>
</tr>
</thead>
<tbody role="rowgroup">
<tr *brnCalendarWeek="let week" class="mt-2 flex w-full">
@for (date of week; track _dateAdapter.getTime(date)) {
<td
brnCalendarCell
class="data-[selected]:data-[outside]:bg-accent/50 data-[selected]:bg-accent relative h-8 w-8 p-0 text-center text-sm focus-within:relative focus-within:z-20 first:data-[selected]:rounded-l-md last:data-[selected]:rounded-r-md [&:has([aria-selected].day-range-end)]:rounded-r-md"
>
<button brnCalendarCellButton [date]="date" [class]="_btnClass">
{{ _dateAdapter.getDate(date) }}
</button>
</td>
}
</tr>
</tbody>
</table>
</div>
</div>
`,
})
export class HlmCalendarMulti<T> {
public readonly calendarClass = input<ClassValue>('');
protected readonly _computedCalenderClass = computed(() => hlm('rounded-md border p-3', this.calendarClass()));
/** Access the calendar i18n */
protected readonly _i18n = injectBrnCalendarI18n();
/** Access the date time adapter */
protected readonly _dateAdapter = injectDateAdapter<T>();
/** The minimum date that can be selected.*/
public readonly min = input<T>();
/** The maximum date that can be selected. */
public readonly max = input<T>();
/** Show dropdowns to navigate between months or years. */
public readonly captionLayout = input<'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years'>('label');
/** The minimum selectable dates. */
public readonly minSelection = input<number, NumberInput>(undefined, {
transform: numberAttribute,
});
/** The maximum selectable dates. */
public readonly maxSelection = input<number, NumberInput>(undefined, {
transform: numberAttribute,
});
/** Determine if the date picker is disabled. */
public readonly disabled = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
/** The selected value. */
public readonly date = model<T[]>();
/** Whether a specific date is disabled. */
public readonly dateDisabled = input<(date: T) => boolean>(() => false);
/** The day the week starts on */
public readonly weekStartsOn = input<Weekday, NumberInput>(undefined, {
transform: (v: unknown) => numberAttribute(v) as Weekday,
});
/** The default focused date. */
public readonly defaultFocusedDate = input<T>();
/** Access the calendar directive */
private readonly _calendar = viewChild.required(BrnCalendarMulti);
/** Get the heading for the current month and year */
protected readonly _heading = computed(() => {
const config = this._i18n.config();
const date = this._calendar().focusedDate();
return {
header: config.formatHeader(this._dateAdapter.getMonth(date), this._dateAdapter.getYear(date)),
month: config.formatMonth(this._dateAdapter.getMonth(date)),
year: config.formatYear(this._dateAdapter.getYear(date)),
};
});
protected readonly _btnClass = hlm(
buttonVariants({ variant: 'ghost' }),
'size-8 p-0 font-normal aria-selected:opacity-100',
'data-[outside]:text-muted-foreground data-[outside]:aria-selected:bg-accent/50 data-[outside]:aria-selected:text-muted-foreground data-[outside]:opacity-50 data-[outside]:aria-selected:opacity-30',
'data-[today]:bg-accent data-[today]:text-accent-foreground',
'data-[selected]:bg-primary data-[selected]:text-primary-foreground data-[selected]:hover:bg-primary data-[selected]:hover:text-primary-foreground data-[selected]:focus:bg-primary data-[selected]:focus:text-primary-foreground',
'data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',
'dark:hover:text-accent-foreground',
);
protected readonly _selectClass = 'gap-0 px-1.5 py-2 [&>ng-icon]:ml-1';
}
@Component({
selector: 'hlm-calendar-range',
imports: [BrnCalendarImports, NgIcon, HlmIcon, HlmSelectImports, NgTemplateOutlet],
viewProviders: [provideIcons({ lucideChevronLeft, lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div
brnCalendarRange
[min]="min()"
[max]="max()"
[disabled]="disabled()"
[(startDate)]="startDate"
[(endDate)]="endDate"
[dateDisabled]="dateDisabled()"
[weekStartsOn]="weekStartsOn()"
[defaultFocusedDate]="defaultFocusedDate()"
[class]="_computedCalenderClass()"
>
<div class="inline-flex flex-col space-y-4">
<!-- Header -->
<div class="space-y-4">
<div class="relative flex items-center justify-center pt-1">
<div class="flex w-full items-center justify-center gap-1.5">
<ng-template #month>
<hlm-select brnCalendarMonthSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (month of _i18n.config().months(); track month) {
<hlm-select-item [value]="month">{{ month }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
<ng-template #year>
<hlm-select brnCalendarYearSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (year of _i18n.config().years(); track year) {
<hlm-select-item [value]="year">{{ year }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
@let heading = _heading();
@switch (captionLayout()) {
@case ('dropdown') {
<ng-container [ngTemplateOutlet]="month" />
<ng-container [ngTemplateOutlet]="year" />
}
@case ('dropdown-months') {
<ng-container [ngTemplateOutlet]="month" />
<div brnCalendarHeader class="text-sm font-medium">{{ heading.year }}</div>
}
@case ('dropdown-years') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.month }}</div>
<ng-container [ngTemplateOutlet]="year" />
}
@case ('label') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.header }}</div>
}
}
</div>
<div class="flex items-center space-x-1">
<button
brnCalendarPreviousButton
class="ring-offset-background focus-visible:ring-ring border-input hover:bg-accent hover:text-accent-foreground absolute left-1 inline-flex h-7 w-7 items-center justify-center rounded-md border bg-transparent p-0 text-sm font-medium whitespace-nowrap opacity-50 transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronLeft" size="sm" />
</button>
<button
brnCalendarNextButton
class="ring-offset-background focus-visible:ring-ring border-input hover:bg-accent hover:text-accent-foreground absolute right-1 inline-flex h-7 w-7 items-center justify-center rounded-md border bg-transparent p-0 text-sm font-medium whitespace-nowrap opacity-50 transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronRight" size="sm" />
</button>
</div>
</div>
</div>
<table class="w-full border-collapse space-y-1" brnCalendarGrid>
<thead>
<tr class="flex">
<th
*brnCalendarWeekday="let weekday"
scope="col"
class="text-muted-foreground w-8 rounded-md text-[0.8rem] font-normal"
[attr.aria-label]="_i18n.config().labelWeekday(weekday)"
>
{{ _i18n.config().formatWeekdayName(weekday) }}
</th>
</tr>
</thead>
<tbody role="rowgroup">
<tr *brnCalendarWeek="let week" class="mt-2 flex w-full">
@for (date of week; track _dateAdapter.getTime(date)) {
<td
brnCalendarCell
class="data-[selected]:data-[outside]:bg-accent/50 data-[selected]:bg-accent relative h-8 w-8 p-0 text-center text-sm focus-within:relative focus-within:z-20 first:data-[selected]:rounded-l-md last:data-[selected]:rounded-r-md [&:has([aria-selected].day-range-end)]:rounded-r-md"
>
<button brnCalendarCellButton [date]="date" [class]="_btnClass">
{{ _dateAdapter.getDate(date) }}
</button>
</td>
}
</tr>
</tbody>
</table>
</div>
</div>
`,
})
export class HlmCalendarRange<T> {
public readonly calendarClass = input<ClassValue>('');
protected readonly _computedCalenderClass = computed(() => hlm('rounded-md border p-3', this.calendarClass()));
/** Access the calendar i18n */
protected readonly _i18n = injectBrnCalendarI18n();
/** Access the date time adapter */
protected readonly _dateAdapter = injectDateAdapter<T>();
/** The minimum date that can be selected.*/
public readonly min = input<T>();
/** The maximum date that can be selected. */
public readonly max = input<T>();
/** Show dropdowns to navigate between months or years. */
public readonly captionLayout = input<'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years'>('label');
/** Determine if the date picker is disabled. */
public readonly disabled = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
/** The start date of the range. */
public readonly startDate = model<T>();
/** The end date of the range. */
public readonly endDate = model<T>();
/** Whether a specific date is disabled. */
public readonly dateDisabled = input<(date: T) => boolean>(() => false);
/** The day the week starts on */
public readonly weekStartsOn = input<Weekday, NumberInput>(undefined, {
transform: (v: unknown) => numberAttribute(v) as Weekday,
});
/** The default focused date. */
public readonly defaultFocusedDate = input<T>();
/** Access the calendar directive */
private readonly _calendar = viewChild.required(BrnCalendarRange);
/** Get the heading for the current month and year */
protected readonly _heading = computed(() => {
const config = this._i18n.config();
const date = this._calendar().focusedDate();
return {
header: config.formatHeader(this._dateAdapter.getMonth(date), this._dateAdapter.getYear(date)),
month: config.formatMonth(this._dateAdapter.getMonth(date)),
year: config.formatYear(this._dateAdapter.getYear(date)),
};
});
protected readonly _btnClass = hlm(
buttonVariants({ variant: 'ghost' }),
'size-8 p-0 font-normal aria-selected:opacity-100',
'data-[outside]:text-muted-foreground data-[outside]:aria-selected:text-muted-foreground',
'data-[today]:bg-accent data-[today]:text-accent-foreground',
'data-[selected]:bg-primary data-[selected]:text-primary-foreground data-[selected]:focus:bg-primary data-[selected]:focus:text-primary-foreground',
'data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',
'data-[range-start]:rounded-l-md',
'data-[range-end]:rounded-r-md',
'data-[range-between]:bg-accent data-[range-between]:text-accent-foreground data-[range-between]:rounded-none',
'dark:hover:text-accent-foreground',
);
protected readonly _selectClass = 'gap-0 px-1.5 py-2 [&>ng-icon]:ml-1';
}
@Component({
selector: 'hlm-calendar',
imports: [BrnCalendarImports, NgIcon, HlmIcon, HlmSelectImports, NgTemplateOutlet],
viewProviders: [provideIcons({ lucideChevronLeft, lucideChevronRight })],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div
brnCalendar
[min]="min()"
[max]="max()"
[disabled]="disabled()"
[(date)]="date"
[dateDisabled]="dateDisabled()"
[weekStartsOn]="weekStartsOn()"
[defaultFocusedDate]="defaultFocusedDate()"
[class]="_computedCalenderClass()"
>
<div class="inline-flex flex-col space-y-4">
<!-- Header -->
<div class="space-y-4">
<div class="relative flex items-center justify-center pt-1">
<div class="flex w-full items-center justify-center gap-1.5">
<ng-template #month>
<hlm-select brnCalendarMonthSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (month of _i18n.config().months(); track month) {
<hlm-select-item [value]="month">{{ month }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
<ng-template #year>
<hlm-select brnCalendarYearSelect>
<hlm-select-trigger size="sm" [class]="_selectClass">
<hlm-select-value />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal class="max-h-80">
<hlm-select-group>
@for (year of _i18n.config().years(); track year) {
<hlm-select-item [value]="year">{{ year }}</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</ng-template>
@let heading = _heading();
@switch (captionLayout()) {
@case ('dropdown') {
<ng-container [ngTemplateOutlet]="month" />
<ng-container [ngTemplateOutlet]="year" />
}
@case ('dropdown-months') {
<ng-container [ngTemplateOutlet]="month" />
<div brnCalendarHeader class="text-sm font-medium">{{ heading.year }}</div>
}
@case ('dropdown-years') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.month }}</div>
<ng-container [ngTemplateOutlet]="year" />
}
@case ('label') {
<div brnCalendarHeader class="text-sm font-medium">{{ heading.header }}</div>
}
}
</div>
<div class="flex items-center space-x-1">
<button
brnCalendarPreviousButton
class="focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground text-popover-foreground absolute left-1 inline-flex size-8 items-center justify-center rounded-md bg-transparent p-0 text-sm font-medium whitespace-nowrap transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronLeft" size="sm" />
</button>
<button
brnCalendarNextButton
class="focus-visible:ring-ring hover:bg-accent hover:text-accent-foreground text-popover-foreground absolute right-1 inline-flex size-8 items-center justify-center rounded-md bg-transparent p-0 text-sm font-medium whitespace-nowrap transition-colors hover:opacity-100 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
>
<ng-icon hlm name="lucideChevronRight" size="sm" />
</button>
</div>
</div>
</div>
<table class="w-full border-collapse space-y-1" brnCalendarGrid>
<thead>
<tr class="flex">
<th
*brnCalendarWeekday="let weekday"
scope="col"
class="text-muted-foreground w-8 rounded-md text-[0.8rem] font-normal"
[attr.aria-label]="_i18n.config().labelWeekday(weekday)"
>
{{ _i18n.config().formatWeekdayName(weekday) }}
</th>
</tr>
</thead>
<tbody role="rowgroup">
<tr *brnCalendarWeek="let week" class="mt-2 flex w-full">
@for (date of week; track _dateAdapter.getTime(date)) {
<td
brnCalendarCell
class="data-[selected]:data-[outside]:bg-accent/50 data-[selected]:bg-accent relative size-8 p-0 text-center text-sm focus-within:relative focus-within:z-20 first:data-[selected]:rounded-l-md last:data-[selected]:rounded-r-md [&:has([aria-selected].day-range-end)]:rounded-r-md"
>
<button brnCalendarCellButton [date]="date" [class]="_btnClass">
{{ _dateAdapter.getDate(date) }}
</button>
</td>
}
</tr>
</tbody>
</table>
</div>
</div>
`,
})
export class HlmCalendar<T> {
public readonly calendarClass = input<ClassValue>('');
protected readonly _computedCalenderClass = computed(() => hlm('rounded-md border p-3', this.calendarClass()));
/** Access the calendar i18n */
protected readonly _i18n = injectBrnCalendarI18n();
/** Access the date time adapter */
protected readonly _dateAdapter = injectDateAdapter<T>();
/** The minimum date that can be selected.*/
public readonly min = input<T>();
/** The maximum date that can be selected. */
public readonly max = input<T>();
/** Show dropdowns to navigate between months or years. */
public readonly captionLayout = input<'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years'>('label');
/** Determine if the date picker is disabled. */
public readonly disabled = input<boolean, BooleanInput>(false, {
transform: booleanAttribute,
});
/** The selected value. */
public readonly date = model<T>();
/** Whether a specific date is disabled. */
public readonly dateDisabled = input<(date: T) => boolean>(() => false);
/** The day the week starts on */
public readonly weekStartsOn = input<Weekday, NumberInput>(undefined, {
transform: (v: unknown) => numberAttribute(v) as Weekday,
});
/** The default focused date. */
public readonly defaultFocusedDate = input<T>();
/** Access the calendar directive */
private readonly _calendar = viewChild.required(BrnCalendar);
/** Get the heading for the current month and year */
protected readonly _heading = computed(() => {
const config = this._i18n.config();
const date = this._calendar().focusedDate();
return {
header: config.formatHeader(this._dateAdapter.getMonth(date), this._dateAdapter.getYear(date)),
month: config.formatMonth(this._dateAdapter.getMonth(date)),
year: config.formatYear(this._dateAdapter.getYear(date)),
};
});
protected readonly _btnClass = hlm(
buttonVariants({ variant: 'ghost' }),
'size-8 p-0 font-normal aria-selected:opacity-100',
'data-[outside]:text-muted-foreground data-[outside]:aria-selected:bg-accent/50 data-[outside]:aria-selected:text-muted-foreground data-[outside]:opacity-50 data-[outside]:aria-selected:opacity-30',
'data-[today]:bg-accent data-[today]:text-accent-foreground',
'data-[selected]:bg-primary data-[selected]:text-primary-foreground data-[selected]:hover:bg-primary dark:hover:text-accent-foreground data-[selected]:focus:bg-primary data-[selected]:focus:text-primary-foreground',
'data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',
'dark:hover:text-accent-foreground',
);
protected readonly _selectClass = 'gap-0 px-1.5 py-2 [&>ng-icon]:ml-1';
}
export const HlmCalendarImports = [HlmCalendar, HlmCalendarMulti, HlmCalendarRange] as const;Usage
import { HlmCalendarImports } from '@spartan-ng/helm/calendar';<hlm-calendar [(date)]="selectedDate" [min]="minDate" [max]="maxDate" />Internationalization
The calendar supports internationalization (i18n) via the BrnCalendarI18nService . By default, weekday names and month headers are rendered in English. You can provide a custom configuration globally or swap it at runtime to support multiple locales.
Global Configuration
Use provideBrnCalendarI18n in your app bootstrap to configure labels and formats globally:
import { bootstrapApplication } from '@angular/platform-browser';
import { provideBrnCalendarI18n } from '@spartan-ng/brain/calendar';
bootstrapApplication(App, {
providers: [
provideBrnCalendarI18n({
formatWeekdayName: (i) => ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'][i],
formatHeader: (m, y) =>
new Date(y, m).toLocaleDateString('de-DE', {
month: 'long',
year: 'numeric',
}),
labelPrevious: () => 'Vorheriger Monat',
labelNext: () => 'Nächster Monat',
labelWeekday: (i) => ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'][i],
firstDayOfWeek: () => 1,
}),
],
});Runtime Configuration
You can dynamically switch calendar language at runtime by injecting BrnCalendarI18nService and calling use() :
import { injectBrnCalendarI18n } from '@spartan-ng/brain/calendar';
@Component({...})
export class CalendarPage {
private readonly _i18n = injectBrnCalendarI18n();
switchToFrench() {
this._i18n.use({
...,
labelNext: () => 'Mois suivant',
labelPrevious: () => 'Mois précédent',
...
});
}
}Examples
Multiple Selection
Use hlm-calendar-multi for multiple date selection. Limit the selectable dates using minSelection and maxSelection inputs.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
import { Component } from '@angular/core';
import { HlmCalendarImports } from '@spartan-ng/helm/calendar';
@Component({
selector: 'spartan-calendar-multiple',
imports: [HlmCalendarImports],
template: `
<hlm-calendar-multi
[(date)]="selectedDates"
[min]="minDate"
[max]="maxDate"
[minSelection]="2"
[maxSelection]="6"
/>
`,
})
export class CalendarMultipleExample {
/** The selected date */
public selectedDates = [new Date()];
/** The minimum date */
public minDate = new Date(2023, 0, 1);
/** The maximum date */
public maxDate = new Date(2030, 11, 31);
}Range Selection
Use hlm-calendar-range for range date selection. Set the range by using startDate and endDate inputs.
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
import { Component } from '@angular/core';
import { HlmCalendarImports } from '@spartan-ng/helm/calendar';
@Component({
selector: 'spartan-calendar-range',
imports: [HlmCalendarImports],
template: `
<hlm-calendar-range [(startDate)]="start" [(endDate)]="end" [min]="minDate" [max]="maxDate" />
`,
})
export class CalendarRangeExample {
/** The selected date */
public start = new Date();
public end = new Date(this.start.getTime() + 5 * 24 * 60 * 60 * 1000);
/** The minimum date */
public minDate = new Date(2023, 0, 1);
/** The maximum date */
public maxDate = new Date(2030, 11, 31);
}Month and Year Selector
| Su | Mo | Tu | We | Th | Fr | Sa |
|---|---|---|---|---|---|---|
import { Component, model } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HlmCalendar } from '@spartan-ng/helm/calendar';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-calendar-year-and-month',
imports: [HlmCalendar, HlmSelectImports, FormsModule],
host: {
class: 'flex flex-col gap-4',
},
template: `
<hlm-calendar [captionLayout]="_captionLayout()" />
<hlm-select class="inline-block" [(ngModel)]="_captionLayout" [itemToString]="itemToString">
<hlm-select-trigger class="w-full">
<hlm-select-value placeholder="Select an option" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-item value="dropdown">Month and Year</hlm-select-item>
<hlm-select-item value="dropdown-months">Only Month</hlm-select-item>
<hlm-select-item value="dropdown-years">Only Year</hlm-select-item>
</hlm-select-group>
</hlm-select-content>
</hlm-select>
`,
})
export class CalendarYearAndMonthExample {
protected readonly _captionLayout = model<'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years'>('dropdown');
public readonly options = [
{ value: 'dropdown', label: 'Month and Year' },
{ value: 'dropdown-months', label: 'Only Month' },
{ value: 'dropdown-years', label: 'Only Year' },
];
public readonly itemToString = (value: string) => this.options.find((option) => option.value === value)?.label || '';
}Brain API
BrnCalendarCellButton
Selector: button[brnCalendarCellButton]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| date* (required) | T | - | The date this cell represents |
BrnCalendarCell
Selector: [brnCalendarCell]
BrnCalendarGrid
Selector: [brnCalendarGrid]
BrnCalendarHeader
Selector: [brnCalendarHeader]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | `brn-calendar-header-${++uniqueId}` | The unique id for the header |
BrnCalendarMonthSelect
Selector: brnSelect[brnCalendarMonthSelect],hlm-select[brnCalendarMonthSelect]
BrnCalendarNextButton
Selector: [brnCalendarNextButton]
BrnCalendarPreviousButton
Selector: [brnCalendarPreviousButton]
BrnCalendarWeek
Selector: [brnCalendarWeek]
BrnCalendarWeekday
Selector: [brnCalendarWeekday]
BrnCalendarYearSelect
Selector: brnSelect[brnCalendarYearSelect],hlm-select[brnCalendarYearSelect]
BrnCalendar
Selector: [brnCalendar]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| date | T | - | The selected value. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| dateChange | T | - | The selected value. |
BrnCalendarMulti
Selector: [brnCalendarMulti]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| minSelection | number | undefined | The minimum selectable dates. |
| maxSelection | number | undefined | The maximum selectable dates. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| date | T[] | - | The selected value. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| dateChange | T[] | - | The selected value. |
BrnCalendarRange
Selector: [brnCalendarRange]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| startDate | T | - | The selected start date |
| endDate | T | - | The selected end date |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| startDateChange | T | - | The selected start date |
| endDateChange | T | - | The selected end date |
Helm API
HlmCalendarMulti
Selector: hlm-calendar-multi
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| calendarClass | ClassValue | - | - |
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| captionLayout | 'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years' | label | Show dropdowns to navigate between months or years. |
| minSelection | number | undefined | The minimum selectable dates. |
| maxSelection | number | undefined | The maximum selectable dates. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| date | T[] | - | The selected value. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| dateChange | T[] | - | The selected value. |
HlmCalendarRange
Selector: hlm-calendar-range
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| calendarClass | ClassValue | - | - |
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| captionLayout | 'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years' | label | Show dropdowns to navigate between months or years. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| startDate | T | - | The start date of the range. |
| endDate | T | - | The end date of the range. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| startDateChange | T | - | The start date of the range. |
| endDateChange | T | - | The end date of the range. |
HlmCalendar
Selector: hlm-calendar
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| calendarClass | ClassValue | - | - |
| min | T | - | The minimum date that can be selected. |
| max | T | - | The maximum date that can be selected. |
| captionLayout | 'dropdown' | 'label' | 'dropdown-months' | 'dropdown-years' | label | Show dropdowns to navigate between months or years. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| dateDisabled | (date: T) => boolean | () => false | Whether a specific date is disabled. |
| weekStartsOn | Weekday | undefined | The day the week starts on |
| defaultFocusedDate | T | - | The default focused date. |
| date | T | - | The selected value. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| dateChange | T | - | The selected value. |
On This Page