Getting Started
UI
Components
- 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
Forms
Stack
Slider
An input where the user selects a value from within a given range.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-preview',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" />
`,
})
export class SliderPreview {
public readonly value = signal([75]);
}Installation
ng g @spartan-ng/cli:ui slidernx g @spartan-ng/cli:ui sliderimport { 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 { BrnSlider, BrnSliderImports, injectBrnSlider } from '@spartan-ng/brain/slider';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Component({
selector: 'hlm-slider, brn-slider [hlm]',
imports: [BrnSliderImports],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnSlider,
inputs: [
'id',
'value',
'disabled',
'min',
'max',
'step',
'minStepsBetweenThumbs',
'inverted',
'orientation',
'showTicks',
'maxTicks',
'tickLabelInterval',
'formatTick',
'draggableRange',
'draggableRangeOnly',
'aria-label',
'aria-labelledby',
],
outputs: ['valueChange'],
},
],
template: `
<div class="relative flex w-full items-center group-data-vertical:w-auto group-data-vertical:flex-col">
<div
brnSliderTrack
class="bg-muted relative grow overflow-hidden rounded-full data-horizontal:h-1 data-horizontal:w-full data-vertical:h-full data-vertical:w-1"
>
<div
class="bg-primary absolute select-none data-draggable-range:cursor-move data-horizontal:h-full data-vertical:w-full"
brnSliderRange
></div>
</div>
@for (i of _slider.thumbIndexes(); track i) {
<span
class="border-ring ring-ring/50 absolute block size-3 shrink-0 rounded-full border bg-white transition-[color,box-shadow] select-none after:absolute after:-inset-2 hover:ring-[3px] focus-visible:ring-[3px] focus-visible:outline-hidden active:ring-[3px]"
brnSliderThumb
></span>
}
</div>
@if (_slider.showTicks()) {
<div
class="text-muted-foreground mt-3 flex w-full items-start justify-between gap-1 px-1.5 text-xs font-medium group-data-horizontal:group-data-inverted:flex-row-reverse group-data-vertical:ms-3 group-data-vertical:mt-0 group-data-vertical:w-auto group-data-vertical:flex-col-reverse group-data-vertical:px-0 group-data-vertical:py-1.5 group-data-vertical:group-data-inverted:flex-col"
>
<div
*brnSliderTick="let tick; let formattedTick = formattedTick"
class="group flex w-0 flex-col items-center justify-center gap-2 group-data-vertical:h-0 group-data-vertical:w-auto group-data-vertical:flex-row"
>
<div
class="bg-muted-foreground/70 h-1 w-px group-data-vertical:h-px group-data-vertical:w-1 group-data-horizontal:group-data-[skip]:h-0.5 group-data-vertical:group-data-[skip]:w-0.5"
></div>
<div class="text-center group-data-[skip]:opacity-0">{{ formattedTick }}</div>
</div>
</div>
}
`,
})
export class HlmSlider {
protected readonly _slider = injectBrnSlider();
constructor() {
classes(() => [
'group flex w-full touch-none flex-col select-none data-vertical:h-full data-vertical:min-h-40 data-vertical:w-auto data-vertical:flex-row data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
]);
}
}
export const HlmSliderImports = [HlmSlider] as const;Usage
import { HlmSliderImports } from '@spartan-ng/helm/slider';<hlm-slider />Examples
Range
Use an array with two values for a range slider.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-range',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" />
`,
})
export class SliderRange {
public readonly value = signal([25, 50]);
}Multiple Thumbs
Use an array with multiple values for multiple thumbs.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-multiple-thumbs',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" />
`,
})
export class SliderMultipleThumbs {
public readonly value = signal([10, 20, 70]);
}Vertical
Use orientation="vertical" for a vertical slider.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-vertical',
imports: [HlmSliderImports],
styles: `
:host {
display: flex;
gap: 1.5rem;
}
`,
template: `
<hlm-slider [(value)]="value" orientation="vertical" />
<hlm-slider [(value)]="value2" orientation="vertical" />
`,
})
export class SliderVertical {
public readonly value = signal([50]);
public readonly value2 = signal([25]);
}Disabled
Use the disabled input to disable the slider.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-disabled',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" [disabled]="true" />
`,
})
export class SliderDisabled {
public readonly value = signal([50]);
}Ticks
0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-ticks',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" [showTicks]="true" />
`,
})
export class SliderTicks {
public readonly value = signal([50]);
}Ticks with label
0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
import { Component, signal } from '@angular/core';
import { HlmLabel } from '@spartan-ng/helm/label';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-ticks-with-label',
imports: [HlmSliderImports, HlmLabel],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<div class="flex flex-col gap-2">
<label hlmLabel for="volume">Volume</label>
<hlm-slider id="volume" [(value)]="value" [showTicks]="true" />
</div>
`,
})
export class SliderTicksWithLabel {
public readonly value = signal([50]);
}Prevent thumb overlap
Use minStepsBetweenThumbs to avoid thumbs with equal values.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-prevent-thumb-overlap',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" [step]="10" [minStepsBetweenThumbs]="1" />
`,
})
export class SliderPreventThumbOverlap {
public readonly value = signal([20, 50]);
}Draggable Range
Use draggableRange to enable moving all thumbs together when dragging by the selected range.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-draggable-range',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" [draggableRange]="true" />
`,
})
export class SliderDraggableRange {
public readonly value = signal([25, 50]);
}Draggable Range Only
Use draggableRangeOnly in pair with draggableRange to allow only dragging the range.
import { Component, signal } from '@angular/core';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-draggable-range-only',
imports: [HlmSliderImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<hlm-slider [(value)]="value" [draggableRange]="true" [draggableRangeOnly]="true" />
`,
})
export class SliderDraggableRangeOnly {
public readonly value = signal([25, 50]);
}Form
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-slider-form',
imports: [HlmSliderImports, ReactiveFormsModule, HlmButtonImports, HlmFieldImports],
styles: `
:host {
display: block;
width: 60%;
}
`,
template: `
<form class="space-y-6" [formGroup]="form" (ngSubmit)="submit()">
<hlm-field>
<label hlmFieldLabel for="volume">Volume</label>
<hlm-slider id="volume" formControlName="volume" />
<p hlmFieldDescription>Set your speaker volume.</p>
</hlm-field>
<hlm-field orientation="horizontal">
<button hlmBtn type="submit">Submit</button>
</hlm-field>
</form>
`,
})
export class SliderForm {
private readonly _formBuilder = inject(FormBuilder);
public form = this._formBuilder.group({
volume: [[25], Validators.required],
});
submit() {
console.log(this.form.value);
}
}Brain API
BrnSliderRange
Selector: [brnSliderRange]
BrnSliderThumb
Selector: [brnSliderThumb]
BrnSliderTick
Selector: [brnSliderTick]
BrnSliderTrack
Selector: [brnSliderTrack]
BrnSlider
Selector: [brnSlider]
ExportAs: brnSlider
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | `brn-slider-${++nextId}` | Unique identifier for the slider element. Auto-generated if not provided. |
| aria-label | string | null | null | Accessibility label for the slider. Forwarded to all thumbs. |
| aria-labelledby | string | null | null | ID of the element that labels this slider for accessibility. Forwarded to all thumbs. |
| min | number | 0 | Minimum allowed slider value. |
| max | number | 100 | Maximum allowed slider value. |
| step | number | 1 | Step increment used when changing values. |
| minStepsBetweenThumbs | number | 0 | Minimum number of steps required between thumbs in a range slider. |
| disabled | boolean | false | Whether the slider is disabled. |
| inverted | boolean | false | Whether the slider direction is inverted. |
| orientation | 'horizontal' | 'vertical' | horizontal | Slider orientation. |
| showTicks | boolean | false | Whether tick marks should be displayed. |
| maxTicks | number | 25 | Maximum number of ticks to render. Excess ticks are evenly distributed. |
| tickLabelInterval | number | 2 | Interval at which tick labels are shown. A value of `2` shows a label every second tick. |
| formatTick | (tick: number) => string | (tick) => tick.toString() | Defines how the tick should be displayed in the UI. |
| draggableRange | boolean | false | Whether dragging the selected range should move all thumbs together. |
| draggableRangeOnly | boolean | false | Whether only dragging the range should work (overrides normal track clicks). |
| value | number[] | [] | The current slider value(s). For single-thumb sliders, this contains one value. For range sliders, values are kept sorted in ascending order. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| valueChange | number[] | - | Emits when the value changes. |
Helm API
HlmSlider
Selector: hlm-slider, brn-slider [hlm]
On This Page
Stop configuring. Start shipping.
Zerops powers spartan.ng and Angular teams worldwide.
One-command deployment. Zero infrastructure headaches.
Deploy with Zerops