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
Radio Group
A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HlmLabelImports } from '@spartan-ng/helm/label';
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';
@Component({
selector: 'spartan-radio-group-preview',
imports: [FormsModule, HlmRadioGroupImports, HlmLabelImports],
template: `
<hlm-radio-group [(ngModel)]="spacing">
<div class="flex items-center gap-3">
<hlm-radio value="default" id="r1" disabled>
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="r1">Default</label>
</div>
<div class="flex items-center gap-3">
<hlm-radio value="comfortable" id="r2">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="r2">Comfortable</label>
</div>
<div class="flex items-center gap-3">
<hlm-radio value="compact" id="r3">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="r3">Compact</label>
</div>
</hlm-radio-group>
`,
})
export class RadioGroupPreview {
public spacing = 'comfortable';
}Installation
ng g @spartan-ng/cli:ui radio-groupnx g @spartan-ng/cli:ui radio-groupimport { DestroyRef, ElementRef, HostAttributeToken, Injector, PLATFORM_ID, effect, inject, runInInjectionContext } from '@angular/core';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
import { twMerge } from 'tailwind-merge';
export function hlm(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
// Global map to track class managers per element
const elementClassManagers = new WeakMap<HTMLElement, ElementClassManager>();
// Global mutation observer for all elements
let globalObserver: MutationObserver | null = null;
const observedElements = new Set<HTMLElement>();
interface ElementClassManager {
element: HTMLElement;
sources: Map<number, { classes: Set<string>; order: number }>;
baseClasses: Set<string>;
isUpdating: boolean;
nextOrder: number;
hasInitialized: boolean;
restoreRafId: number | null;
/** Transitions are suppressed until the first effect writes correct classes */
transitionsSuppressed: boolean;
/** Original inline transition value to restore after suppression (empty string = none was set) */
previousTransition: string;
/** Original inline transition priority to preserve !important when restoring */
previousTransitionPriority: string;
}
let sourceCounter = 0;
/**
* This function dynamically adds and removes classes for a given element without requiring
* the a class binding (e.g. `[class]="..."`) which may interfere with other class bindings.
*
* 1. This will merge the existing classes on the element with the new classes.
* 2. It will also remove any classes that were previously added by this function but are no longer present in the new classes.
* 3. Multiple calls to this function on the same element will be merged efficiently.
*/
export function classes(computed: () => ClassValue[] | string, options: ClassesOptions = {}) {
runInInjectionContext(options.injector ?? inject(Injector), () => {
const elementRef = options.elementRef ?? inject(ElementRef);
const platformId = inject(PLATFORM_ID);
const destroyRef = inject(DestroyRef);
const baseClasses = inject(new HostAttributeToken('class'), { optional: true });
const element = elementRef.nativeElement;
// Create unique identifier for this source
const sourceId = sourceCounter++;
// Get or create the class manager for this element
let manager = elementClassManagers.get(element);
if (!manager) {
// Initialize base classes from variation (host attribute 'class')
const initialBaseClasses = new Set<string>();
if (baseClasses) {
toClassList(baseClasses).forEach((cls) => initialBaseClasses.add(cls));
}
manager = {
element,
sources: new Map(),
baseClasses: initialBaseClasses,
isUpdating: false,
nextOrder: 0,
hasInitialized: false,
restoreRafId: null,
transitionsSuppressed: false,
previousTransition: '',
previousTransitionPriority: '',
};
elementClassManagers.set(element, manager);
// Setup global observer if needed and register this element
setupGlobalObserver(platformId);
observedElements.add(element);
// Suppress transitions until the first effect writes correct classes and
// the browser has painted them. This prevents CSS transition animations
// during hydration when classes change from SSR state to client state.
if (isPlatformBrowser(platformId)) {
manager.previousTransition = element.style.getPropertyValue('transition');
manager.previousTransitionPriority = element.style.getPropertyPriority('transition');
element.style.setProperty('transition', 'none', 'important');
manager.transitionsSuppressed = true;
}
}
// Assign order once at registration time
const sourceOrder = manager.nextOrder++;
function updateClasses(): void {
// Get the new classes from the computed function
const newClasses = toClassList(computed());
// Update this source's classes, keeping the original order
manager!.sources.set(sourceId, {
classes: new Set(newClasses),
order: sourceOrder,
});
// Update the element
updateElement(manager!);
// Re-enable transitions after the first effect writes correct classes.
// Deferred to next animation frame so the browser paints the class change
// with transitions disabled first, then re-enables them.
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
manager!.restoreRafId = requestAnimationFrame(() => {
manager!.restoreRafId = null;
restoreTransitionSuppression(manager!);
});
}
}
// Register cleanup with DestroyRef
destroyRef.onDestroy(() => {
if (manager!.restoreRafId !== null) {
cancelAnimationFrame(manager!.restoreRafId);
manager!.restoreRafId = null;
}
if (manager!.transitionsSuppressed) {
manager!.transitionsSuppressed = false;
restoreTransitionSuppression(manager!);
}
// Remove this source from the manager
manager!.sources.delete(sourceId);
// If no more sources, clean up the manager
if (manager!.sources.size === 0) {
cleanupManager(element);
} else {
// Update element without this source's classes
updateElement(manager!);
}
});
/**
* We need this effect to track changes to the computed classes. Ideally, we would use
* afterRenderEffect here, but that doesn't run in SSR contexts, so we use a standard
* effect which works in both browser and SSR.
*/
effect(updateClasses);
});
}
function restoreTransitionSuppression(manager: ElementClassManager): void {
const prev = manager.previousTransition;
if (prev) {
manager.element.style.setProperty('transition', prev, manager.previousTransitionPriority || undefined);
} else {
manager.element.style.removeProperty('transition');
}
}
// eslint-disable-next-line @typescript-eslint/no-wrapper-object-types
function setupGlobalObserver(platformId: Object): void {
if (isPlatformBrowser(platformId) && !globalObserver) {
// Create single global observer that watches the entire document
globalObserver = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
const element = mutation.target as HTMLElement;
const manager = elementClassManagers.get(element);
// Only process elements we're managing
if (manager && observedElements.has(element)) {
if (manager.isUpdating) continue; // Ignore changes we're making
// Update base classes to include any externally added classes
const currentClasses = toClassList(element.className);
const allSourceClasses = new Set<string>();
// Collect all classes from all sources
for (const source of manager.sources.values()) {
for (const className of source.classes) {
allSourceClasses.add(className);
}
}
// Any classes not from sources become new base classes
manager.baseClasses.clear();
for (const className of currentClasses) {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
}
updateElement(manager);
}
}
}
});
// Start observing the entire document for class attribute changes
globalObserver.observe(document, {
attributes: true,
attributeFilter: ['class'],
subtree: true, // Watch all descendants
});
}
}
function updateElement(manager: ElementClassManager): void {
if (manager.isUpdating) return; // Prevent recursive updates
manager.isUpdating = true;
// Handle initialization: capture base classes after first source registration
if (!manager.hasInitialized && manager.sources.size > 0) {
// Get current classes on element (may include SSR classes)
const currentClasses = toClassList(manager.element.className);
// Get all classes that will be applied by sources
const allSourceClasses = new Set<string>();
for (const source of manager.sources.values()) {
source.classes.forEach((className) => allSourceClasses.add(className));
}
// Only consider classes as "base" if they're not produced by any source
// This prevents SSR-rendered classes from being preserved as base classes
currentClasses.forEach((className) => {
if (!allSourceClasses.has(className)) {
manager.baseClasses.add(className);
}
});
manager.hasInitialized = true;
}
// Get classes from all sources, sorted by registration order (later takes precedence)
const sortedSources = Array.from(manager.sources.entries()).sort(([, a], [, b]) => a.order - b.order);
const allSourceClasses: string[] = [];
for (const [, source] of sortedSources) {
allSourceClasses.push(...source.classes);
}
// Combine base classes with all source classes, ensuring base classes take precedence
const classesToApply =
allSourceClasses.length > 0 || manager.baseClasses.size > 0
? hlm([...allSourceClasses, ...manager.baseClasses])
: '';
// Apply the classes to the element
if (manager.element.className !== classesToApply) {
manager.element.className = classesToApply;
}
manager.isUpdating = false;
}
function cleanupManager(element: HTMLElement): void {
// Remove from global tracking
observedElements.delete(element);
elementClassManagers.delete(element);
// If no more elements being tracked, cleanup global observer
if (observedElements.size === 0 && globalObserver) {
globalObserver.disconnect();
globalObserver = null;
}
}
interface ClassesOptions {
elementRef?: ElementRef<HTMLElement>;
injector?: Injector;
}
// Cache for parsed class lists to avoid repeated string operations
const classListCache = new Map<string, string[]>();
function toClassList(className: string | ClassValue[]): string[] {
// For simple string inputs, use cache to avoid repeated parsing
if (typeof className === 'string' && classListCache.has(className)) {
return classListCache.get(className)!;
}
const result = clsx(className)
.split(' ')
.filter((c) => c.length > 0);
// Cache string results, but limit cache size to prevent memory growth
if (typeof className === 'string' && classListCache.size < 1000) {
classListCache.set(className, result);
}
return result;
}import type, { ClassValue } from 'clsx';
import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnRadio, BrnRadioGroup, type BrnRadioChange } from '@spartan-ng/brain/radio-group';
import { ChangeDetectionStrategy, Component, DOCUMENT, Directive, ElementRef, PLATFORM_ID, Renderer2, booleanAttribute, computed, effect, inject, input, output } from '@angular/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { isPlatformBrowser } from '@angular/common';
import { type BooleanInput } from '@angular/cdk/coercion';
@Directive({
selector: '[hlmRadioGroup],hlm-radio-group',
hostDirectives: [
{
directive: BrnRadioGroup,
inputs: ['name', 'value', 'disabled', 'required'],
outputs: ['valueChange'],
},
BrnFieldControlDescribedBy,
],
host: {
'data-slot': 'radio-group',
'[attr.aria-invalid]': '_ariaInvalid() ? "true" : null',
'[attr.data-invalid]': '_ariaInvalid() ? "true" : null',
'[attr.data-dirty]': '_dirty() ? "true" : null',
'[attr.data-touched]': '_touched() ? "true" : null',
},
})
export class HlmRadioGroup {
public readonly userClass = input<ClassValue>('', { alias: 'class' });
private readonly _brnRadioGroup = inject(BrnRadioGroup);
protected readonly _ariaInvalid = computed(() => this._brnRadioGroup.controlState?.()?.invalid);
protected readonly _touched = computed(() => this._brnRadioGroup.controlState?.()?.touched);
protected readonly _dirty = computed(() => this._brnRadioGroup.controlState?.()?.dirty);
protected readonly _errorState = computed(() => this._brnRadioGroup.controlState?.()?.spartanInvalid);
constructor() {
classes(() => ['grid gap-3', this.userClass(), this._errorState() ? 'data-[invalid=true]:text-destructive' : '']);
}
}
@Component({
selector: 'hlm-radio-indicator',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'data-slot': 'radio-group-indicator',
},
template: `
<div class="group-data-[checked=true]:bg-primary size-2 rounded-full bg-transparent"></div>
`,
})
export class HlmRadioIndicator {
constructor() {
classes(
() =>
'border-input text-primary group-has-[:focus-visible]:border-ring group-has-[:focus-visible]:ring-ring/50 dark:bg-input/30 group-data=[disabled=true]:cursor-not-allowed group-data=[disabled=true]:opacity-50 relative flex aspect-square size-4 shrink-0 items-center justify-center rounded-full border shadow-xs transition-[color,box-shadow] outline-none group-has-[:focus-visible]:ring-[3px]',
);
}
}
@Component({
selector: 'hlm-radio',
imports: [BrnRadio],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[attr.id]': 'null',
'[attr.aria-label]': 'null',
'[attr.aria-labelledby]': 'null',
'[attr.aria-describedby]': 'null',
'[attr.data-disabled]': 'disabled() ? "" : null',
'data-slot': 'radio-group-item',
},
template: `
<brn-radio
[id]="id()"
[class]="_computedClass()"
[value]="value()"
[required]="required()"
[disabled]="disabled()"
[attr.aria-invalid]="_ariaInvalid() ? 'true' : null"
[attr.data-invalid]="_ariaInvalid() ? 'true' : null"
[attr.data-dirty]="_dirty() ? 'true' : null"
[attr.data-touched]="_touched() ? 'true' : null"
[attr.data-matches-spartan-invalid]="_groupSpartanInvalid() ? 'true' : null"
[aria-label]="ariaLabel()"
[aria-labelledby]="ariaLabelledby()"
[aria-describedby]="ariaDescribedby()"
(change)="change.emit($event)"
>
<ng-content select="[target],[indicator],hlm-radio-indicator" indicator />
<ng-content />
</brn-radio>
`,
})
export class HlmRadio<T = unknown> {
private readonly _document = inject(DOCUMENT);
private readonly _renderer = inject(Renderer2);
private readonly _elementRef = inject(ElementRef);
private readonly _isBrowser = isPlatformBrowser(inject(PLATFORM_ID));
private readonly _radioGroup = inject(BrnRadioGroup, { optional: true });
protected readonly _ariaInvalid = computed(() => this._radioGroup?.controlState?.()?.invalid);
protected readonly _touched = computed(() => this._radioGroup?.controlState?.()?.touched);
protected readonly _dirty = computed(() => this._radioGroup?.controlState?.()?.dirty);
protected readonly _groupSpartanInvalid = computed(() => this._radioGroup?.controlState?.()?.spartanInvalid);
protected readonly _errorStateClass = computed(() => (this._groupSpartanInvalid() ? 'text-destructive' : ''));
public readonly userClass = input<ClassValue>('', { alias: 'class' });
protected readonly _computedClass = computed(() =>
hlm(
'group relative flex items-center gap-x-3',
'data-[disabled=true]:cursor-not-allowed data-[disabled=true]:opacity-50',
this.userClass(),
this._errorStateClass(),
),
);
/** Used to set the id on the underlying brn element. */
public readonly id = input<string | undefined>(undefined);
/** Used to set the aria-label attribute on the underlying brn element. */
public readonly ariaLabel = input<string | undefined>(undefined, { alias: 'aria-label' });
/** Used to set the aria-labelledby attribute on the underlying brn element. */
public readonly ariaLabelledby = input<string | undefined>(undefined, { alias: 'aria-labelledby' });
/** Used to set the aria-describedby attribute on the underlying brn element. */
public readonly ariaDescribedby = input<string | undefined>(undefined, { alias: 'aria-describedby' });
/**
* The value this radio button represents.
*/
public readonly value = input.required<T>();
/** Whether the checkbox is required. */
public readonly required = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
/** Whether the checkbox is disabled. */
public readonly disabled = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
/**
* Event emitted when the checked state of this radio button changes.
*/
// eslint-disable-next-line @angular-eslint/no-output-native
public readonly change = output<BrnRadioChange<T>>();
constructor() {
effect(() => {
const isDisabled = this.disabled();
if (!this._elementRef.nativeElement || !this._isBrowser) return;
const labelElement =
this._elementRef.nativeElement.closest('label') ?? this._document.querySelector(`label[for="${this.id()}"]`);
if (!labelElement) return;
this._renderer.setAttribute(labelElement, 'data-disabled', isDisabled ? 'true' : 'false');
});
}
}
export const HlmRadioGroupImports = [HlmRadioGroup, HlmRadio, HlmRadioIndicator] as const;Usage
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';<hlm-radio-group>
<div class="flex items-center gap-3">
<hlm-radio value="option-one" id="option-one">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="option-one"> option-one</label>
</div>
<div class="flex items-center gap-3">
<hlm-radio value="option-two" id="option-two">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="option-two"> option-two</label>
</div>
</hlm-radio-group>Examples
Card Layout
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideCreditCard } from '@ng-icons/lucide';
import { remixAppleFill, remixPaypalFill } from '@ng-icons/remixicon';
import { HlmIconImports } from '@spartan-ng/helm/icon';
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';
import { hlm } from '@spartan-ng/helm/utils';
@Component({
selector: 'spartan-radio-card-preview',
imports: [FormsModule, HlmRadioGroupImports, NgIcon, HlmIconImports],
providers: [provideIcons({ lucideCreditCard, remixPaypalFill, remixAppleFill })],
template: `
<hlm-radio-group class="grid grid-cols-3 gap-4" [(ngModel)]="payment">
<label class="flex items-center" hlmLabel [class]="cardClass">
<hlm-radio value="card">
<ng-icon hlm name="lucideCreditCard" class="mb-3" />
</hlm-radio>
Card
</label>
<label class="flex items-center" hlmLabel [class]="cardClass">
<hlm-radio value="paypal">
<ng-icon hlm name="remixPaypalFill" class="mb-3" />
</hlm-radio>
PayPal
</label>
<label class="flex items-center" hlmLabel [class]="cardClass">
<hlm-radio value="apple">
<ng-icon hlm name="remixAppleFill" class="mb-3" />
</hlm-radio>
Apple
</label>
</hlm-radio-group>
`,
})
export class RadioGroupCard {
public payment = 'card';
public readonly cardClass = hlm(
'relative block space-x-0',
// base card styles
'border-border flex flex-col items-center justify-center rounded-lg border-2 px-4 py-8',
// hover and background styles
'bg-background hover:bg-accent/10 cursor-pointer transition-colors',
// spacing for the icon and text
'[&>span]:mt-4',
// target the checked state properly
'[&:has([data-checked=true])]:border-primary [&:has([data-checked=true])]:border-2',
);
}Form
import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmLabelImports } from '@spartan-ng/helm/label';
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';
@Component({
selector: 'spartan-radio-group-form',
imports: [HlmRadioGroupImports, HlmLabelImports, HlmButtonImports, ReactiveFormsModule],
template: `
<form class="space-y-6" [formGroup]="form" (ngSubmit)="submit()">
<div class="flex flex-col gap-3">
<label hlmLabel>Subscription Plan</label>
<hlm-radio-group formControlName="plan">
<div class="flex items-center gap-3">
<hlm-radio value="monthly" id="monthly">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="monthly">Monthly ($9.99/month)</label>
</div>
<div class="flex items-center gap-3">
<hlm-radio value="yearly" id="yearly">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="yearly">Yearly ($99.99/year)</label>
</div>
<div class="flex items-center gap-3">
<hlm-radio value="lifetime" id="lifetime">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmLabel for="lifetime">Lifetime ($299.99)</label>
</div>
</hlm-radio-group>
</div>
<button hlmBtn type="submit">Submit</button>
</form>
`,
})
export class RadioGroupFormPreview {
private readonly _formBuilder = inject(FormBuilder);
public form = this._formBuilder.group({
plan: ['monthly', Validators.required],
});
submit() {
console.log(this.form.value);
}
}Brain API
BrnRadioGroup
Selector: [brnRadioGroup]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| name | string | `brn-radio-group-${++BrnRadioGroup._nextUniqueId}` | - |
| disabled | boolean | false | Whether the radio group is disabled. |
| required | boolean | false | Whether the radio group should be required. |
| value | T | - | The value of the selected radio button. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| valueChange | T | - | Emits when the value changes. |
| change | BrnRadioChange<T> | - | Event emitted when the group value changes. |
BrnRadio
Selector: brn-radio
ExportAs: brnRadio
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| disabled | boolean | false | Whether the radio button is disabled. |
| id | string | undefined | undefined | The unique ID for the radio button input. If none is supplied, it will be auto-generated. |
| aria-label | string | undefined | undefined | - |
| aria-labelledby | string | undefined | undefined | - |
| aria-describedby | string | undefined | undefined | - |
| value* (required) | T | - | The value this radio button represents. |
| required | boolean | false | Whether the radio button is required. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| change | BrnRadioChange<T> | - | Event emitted when the checked state of this radio button changes. |
Helm API
HlmRadioGroup
Selector: [hlmRadioGroup],hlm-radio-group
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| class | ClassValue | - | - |
HlmRadioIndicator
Selector: hlm-radio-indicator
HlmRadio
Selector: hlm-radio
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| class | ClassValue | - | - |
| id | string | undefined | undefined | Used to set the id on the underlying brn element. |
| aria-label | string | undefined | undefined | Used to set the aria-label attribute on the underlying brn element. |
| aria-labelledby | string | undefined | undefined | Used to set the aria-labelledby attribute on the underlying brn element. |
| aria-describedby | string | undefined | undefined | Used to set the aria-describedby attribute on the underlying brn element. |
| value* (required) | T | - | The value this radio button represents. |
| required | boolean | false | Whether the checkbox is required. |
| disabled | boolean | false | Whether the checkbox is disabled. |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| change | BrnRadioChange<T> | - | Event emitted when the checked state of this radio button changes. |
On This Page
Stop configuring. Start shipping.
Zerops powers spartan.ng and Angular teams worldwide.
One-command deployment. Zero infrastructure headaches.
Deploy with Zerops