- 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
- Form 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
Field
Combine labels, controls, and help text to compose accessible form fields and grouped inputs.
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmCheckboxImports } from '@spartan-ng/helm/checkbox';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
import { HlmSelectImports } from '@spartan-ng/helm/select';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-field-preview',
imports: [
HlmCheckboxImports,
HlmTextareaImports,
HlmButtonImports,
HlmInputImports,
HlmFieldImports,
HlmSelectImports,
ReactiveFormsModule,
],
host: {
class: 'w-full max-w-md',
},
template: `
<form>
<div hlmFieldGroup>
<fieldset hlmFieldSet>
<legend hlmFieldLegend>Payment Method</legend>
<p hlmFieldDescription>All transactions are secure and encrypted</p>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-preview-name-on-card">Name on card</label>
<input hlmInput placeholder="John Doe" id="field-preview-name-on-card" />
</div>
<div hlmField class="col-span-2">
<label hlmFieldLabel for="field-preview-card-number">Card number</label>
<input hlmInput placeholder="1234 1234 1234 1234" id="field-preview-card-number" />
<p hlmFieldDescription>Enter your 16-digit card number</p>
</div>
<div class="grid grid-cols-3 gap-4">
<div hlmField>
<label hlmFieldLabel for="field-exp-month--trigger">Month</label>
<hlm-select id="field-exp-month" class="inline-block">
<hlm-select-trigger class="w-full">
<hlm-select-value placeholder="MM" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-item value="01">01</hlm-select-item>
<hlm-select-item value="02">02</hlm-select-item>
<hlm-select-item value="03">03</hlm-select-item>
<hlm-select-item value="04">04</hlm-select-item>
<hlm-select-item value="05">05</hlm-select-item>
<hlm-select-item value="06">06</hlm-select-item>
<hlm-select-item value="07">07</hlm-select-item>
<hlm-select-item value="08">08</hlm-select-item>
<hlm-select-item value="09">09</hlm-select-item>
<hlm-select-item value="10">10</hlm-select-item>
<hlm-select-item value="11">11</hlm-select-item>
<hlm-select-item value="12">12</hlm-select-item>
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</div>
<div hlmField>
<label hlmFieldLabel for="field-exp-year--trigger">Year</label>
<hlm-select id="field-exp-year" class="inline-block">
<hlm-select-trigger class="w-full">
<hlm-select-value placeholder="YYYY" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
<hlm-select-item value="2024">2024</hlm-select-item>
<hlm-select-item value="2025">2025</hlm-select-item>
<hlm-select-item value="2026">2026</hlm-select-item>
<hlm-select-item value="2027">2027</hlm-select-item>
<hlm-select-item value="2028">2028</hlm-select-item>
<hlm-select-item value="2029">2029</hlm-select-item>
</hlm-select-group>
</hlm-select-content>
</hlm-select>
</div>
<div hlmField>
<label hlmFieldLabel for="field-preview-cvv">CVV</label>
<input hlmInput placeholder="123" id="field-preview-cvv" />
</div>
</div>
</div>
</fieldset>
<hlm-field-separator />
<fieldset hlmFieldSet>
<legend hlmFieldLegend>Billing Address</legend>
<p hlmFieldDescription>The billing address associated with your payment method</p>
<div hlmFieldGroup>
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-preview-billing-address" [checked]="true" />
<label hlmFieldLabel for="field-preview-billing-address">Same as shipping address.</label>
</div>
</div>
</fieldset>
<fieldset hlmFieldSet>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-preview-comments">Comments</label>
<textarea hlmTextarea class="resize-none" id="field-preview-comments"></textarea>
</div>
</div>
</fieldset>
<div hlmField orientation="horizontal">
<button hlmBtn>Submit</button>
<button hlmBtn variant="outline">Cancel</button>
</div>
</div>
</form>
`,
})
export class FieldPreview {
public control = new FormControl('', Validators.required);
}
export const anatomyCode = `
<div hlmField>
<label hlmFieldLabel for="field-preview-fullname">Label</label>
<!-- Input, Select, Switch, etc. -->
<p hlmFieldDescription>Optional helper text.</p>
<hlm-field-error>Validation message.</hlm-field-error>
</div>
`;
export const validationAndErrorCode = `
<div hlmField data-invalid="true">
<label hlmFieldLabel for="validation-error-email">Email</label>
<input hlmInput id="validation-error-email" type="email" aria-invalid="true" />
<hlm-field-error>Enter a valid email address.</hlm-field-error>
</div>
`;Installation
ng g @spartan-ng/cli:ui fieldnx g @spartan-ng/cli:ui fieldimport { 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 { ChangeDetectionStrategy, Component, Directive, computed, input } from '@angular/core';
import { HlmLabel } from '@spartan-ng/helm/label';
import { HlmSeparator } from '@spartan-ng/helm/separator';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { cva, type VariantProps } from 'class-variance-authority';
@Directive({
selector: '[hlmFieldContent],hlm-field-content',
host: {
'data-slot': 'field-content',
},
})
export class HlmFieldContent {
constructor() {
classes(() => 'group/field-content flex flex-1 flex-col gap-1.5 leading-snug');
}
}
@Directive({
selector: '[hlmFieldDescription],hlm-field-description',
host: {
'data-slot': 'field-description',
},
})
export class HlmFieldDescription {
constructor() {
classes(() => [
'text-muted-foreground text-sm leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance',
'last:mt-0 nth-last-2:-mt-1 [[data-variant=legend]+&]:-mt-1.5',
'[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4',
]);
}
}
@Component({
selector: 'hlm-field-error',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div role="alert" data-slot="field-error" [class]="_computedClass()">
<ng-content>
@if (_uniqueErrors().length === 1) {
{{ _uniqueErrors()[0]?.message }}
} @else if (_uniqueErrors().length > 1) {
<ul class="ml-4 flex list-disc flex-col gap-1">
@for (error of _uniqueErrors(); track $index) {
@if (error?.message) {
<li>{{ error?.message }}</li>
}
}
</ul>
}
</ng-content>
</div>
`,
})
export class HlmFieldError {
public readonly userClass = input<ClassValue>('', { alias: 'class' });
public readonly error = input<Array<{ message: string } | undefined>>();
protected readonly _uniqueErrors = computed(() => {
const errors = this.error();
if (!errors?.length) {
return [];
}
return [...new Map(errors.map((err) => [err?.message, err])).values()];
});
protected readonly _computedClass = computed(() => hlm('text-destructive text-sm font-normal', this.userClass()));
}
@Directive({
selector: '[hlmFieldGroup],hlm-field-group',
host: {
'data-slot': 'field-group',
},
})
export class HlmFieldGroup {
constructor() {
classes(
() =>
'group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4',
);
}
}
@Directive({
selector: '[hlmFieldLabel],hlm-field-label',
hostDirectives: [HlmLabel],
host: {
'data-slot': 'field-label',
},
})
export class HlmFieldLabel {
constructor() {
classes(() => [
'group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50',
'has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>*]:data-[slot=field]:p-4',
'has-data-[checked=true]:bg-primary/5 has-data-[checked=true]:border-primary dark:has-data-[checked=true]:bg-primary/10',
'has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10',
]);
}
}
@Directive({
selector: 'legend[hlmFieldLegend]',
host: {
'data-slot': 'field-legend',
'[attr.data-variant]': 'variant()',
},
})
export class HlmFieldLegend {
constructor() {
classes(() => 'mb-3 font-medium data-[variant=label]:text-sm data-[variant=legend]:text-base');
}
public readonly variant = input<'label' | 'legend'>('legend');
}
@Component({
selector: 'hlm-field-separator',
imports: [HlmSeparator],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'data-slot': 'field-separator',
},
template: `
<hlm-separator class="absolute inset-0 top-1/2" />
<span
data-slot="field-separator-content"
class="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
>
<ng-content />
</span>
`,
})
export class HlmFieldSeparator {
constructor() {
classes(() => 'relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2');
}
}
@Directive({
selector: 'fieldset[hlmFieldSet]',
host: {
'data-slot': 'field-set',
},
})
export class HlmFieldSet {
constructor() {
classes(() => [
'flex flex-col gap-6',
'has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3',
]);
}
}
@Directive({
selector: '[hlmFieldTitle],hlm-field-title',
host: {
'data-slot': 'field-label',
},
})
export class HlmFieldTitle {
constructor() {
classes(
() =>
'flex w-fit items-center gap-2 text-sm leading-snug font-medium group-data-[disabled=true]/field:opacity-50',
);
}
}
const fieldVariants = cva('group/field data-[invalid=true]:text-destructive flex w-full gap-3', {
variants: {
orientation: {
vertical: ['flex-col [&>*]:w-full [&>.sr-only]:w-auto'],
horizontal: [
'flex-row items-center',
'[&>[data-slot=field-label]]:flex-auto',
'has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
],
responsive: [
'flex-col @md/field-group:flex-row @md/field-group:items-center [&>*]:w-full @md/field-group:[&>*]:w-auto [&>.sr-only]:w-auto',
'@md/field-group:[&>[data-slot=field-label]]:flex-auto',
'@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px',
],
},
},
defaultVariants: {
orientation: 'vertical',
},
});
export type FieldVariants = VariantProps<typeof fieldVariants>;
@Directive({
selector: '[hlmField],hlm-field',
host: {
role: 'group',
'data-slot': 'field',
'[attr.data-orientation]': 'orientation()',
},
})
export class HlmField {
public readonly orientation = input<FieldVariants['orientation']>('vertical');
constructor() {
classes(() => fieldVariants({ orientation: this.orientation() }));
}
}
export const HlmFieldImports = [
HlmField,
HlmFieldTitle,
HlmFieldContent,
HlmFieldDescription,
HlmFieldError,
HlmFieldLabel,
HlmFieldSeparator,
HlmFieldGroup,
HlmFieldLegend,
HlmFieldSet,
] as const;Usage
import { HlmFieldImports } from "@spartan-ng/helm/field";<fieldset hlmFieldSet>
<legend hlmFieldLegend>Profile</legend>
<p hlmFieldDescription>This appears on invoices and emails.</p>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-preview-fullname">Full name</label>
<input hlmInput id="field-preview-fullname" type="text" placeholder="John Doe" />
<p hlmFieldDescription>This appears on invoices and emails.</p>
</div>
<div hlmField>
<label hlmFieldLabel for="field-preview-username">Username</label>
<input hlmInput id="field-preview-username" type="text" placeholder="john_doe_99" />
<hlm-field-error>Choose another username.</hlm-field-error>
</div>
<div hlmField orientation="horizontal">
<hlm-switch id="field-preview-subscribe-newsletter" />
<label hlmFieldLabel for="field-preview-subscribe-newsletter">Subscribe to the newsletter</label>
</div>
</div>
</fieldset>Anatomy
The Field family is designed for composing accessible forms. A typical field is structured as follows:
<div hlmField>
<label hlmFieldLabel for="field-preview-fullname">Label</label>
<!-- Input, Select, Switch, etc. -->
<p hlmFieldDescription>Optional helper text.</p>
<hlm-field-error>Validation message.</hlm-field-error>
</div>HlmFieldis the core wrapper for a single field.HlmFieldContentis a flex column that groups label and description. Not required if you have no description.- Wrap related fields with
HlmFieldGroup, and useHlmFieldSetwithHlmFieldLegendfor semantic grouping.
Examples
Input
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
@Component({
selector: 'spartan-field-input-preview',
imports: [HlmFieldImports, HlmInputImports],
host: {
class: 'w-full max-w-md',
},
template: `
<fieldset hlmFieldSet>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-input-preview-firstname">Username</label>
<input hlmInput id="field-input-preview-firstname" type="text" placeholder="Alex Cooper" />
<p hlmFieldDescription>Choose a unique username for your account.</p>
</div>
<div hlmField>
<label hlmFieldLabel for="field-input-preview-password">Password</label>
<p hlmFieldDescription>Must be at least 8 characters long.</p>
<input hlmInput id="field-input-preview-password" type="password" placeholder="••••••••" />
</div>
</div>
</fieldset>
`,
})
export class FieldInputPreview {}Textarea
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-field-textarea-preview',
imports: [HlmFieldImports, HlmTextareaImports],
host: {
class: 'w-full max-w-md',
},
template: `
<fieldset hlmFieldSet>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-input-preview-firstname">Feedback</label>
<textarea
hlmTextarea
id="field-input-preview-firstname"
placeholder="Your feedback helps us improve..."
></textarea>
<p hlmFieldDescription>Share your thoughts about our service.</p>
</div>
</div>
</fieldset>
`,
})
export class FieldTextareaPreview {}Select
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmSelectImports } from '@spartan-ng/helm/select';
@Component({
selector: 'spartan-field-select-preview',
imports: [HlmFieldImports, HlmSelectImports],
host: {
class: 'w-full max-w-md',
},
template: `
<fieldset hlmFieldSet>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-select-department">Department</label>
<hlm-select [itemToString]="itemToString">
<hlm-select-trigger class="w-full" buttonId="field-select-department">
<hlm-select-value placeholder="Choose a department" />
</hlm-select-trigger>
<hlm-select-content *hlmSelectPortal>
<hlm-select-group>
@for (department of departments; track department.value) {
<hlm-select-item [value]="department.value">
{{ department.label }}
</hlm-select-item>
}
</hlm-select-group>
</hlm-select-content>
</hlm-select>
<p hlmFieldDescription>Select your department or area of work.</p>
</div>
</div>
</fieldset>
`,
})
export class FieldSelectPreview {
public readonly departments = [
{ value: 'engineering', label: 'Engineering' },
{ value: 'design', label: 'Design' },
{ value: 'marketing', label: 'Marketing' },
{ value: 'sales', label: 'Sales' },
{ value: 'support', label: 'Customer Support' },
{ value: 'hr', label: 'Human Resources' },
{ value: 'finance', label: 'Finance' },
{ value: 'operations', label: 'Operations' },
];
public readonly itemToString = (value: string) => this.departments.find((d) => d.value === value)?.label ?? '';
}Slider
import { Component, signal } from '@angular/core';
import { HlmField, HlmFieldDescription, HlmFieldGroup, HlmFieldLabel, HlmFieldSet } from '@spartan-ng/helm/field';
import { HlmSliderImports } from '@spartan-ng/helm/slider';
@Component({
selector: 'spartan-field-slider-preview',
imports: [HlmFieldSet, HlmFieldGroup, HlmField, HlmFieldLabel, HlmFieldDescription, HlmSliderImports],
host: {
class: 'w-full max-w-md',
},
template: `
<fieldset hlmFieldSet>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-input-preview-firstname">Price Range</label>
<p hlmFieldDescription>Set your budget range ($0 - {{ value() }}).</p>
<hlm-slider [max]="1000" [step]="10" [(value)]="value" />
</div>
</div>
</fieldset>
`,
})
export class FieldSliderPreview {
public readonly value = signal([500]);
}Fieldset
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
@Component({
selector: 'spartan-field-set-preview',
imports: [HlmFieldImports, HlmInputImports],
host: {
class: 'w-full max-w-md space-y-6',
},
template: `
<fieldset hlmFieldSet>
<legend hlmFieldLegend>Address Information</legend>
<p hlmFieldDescription>Choose a unique username for your account.</p>
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-set-street-address">Street Address</label>
<input hlmInput id="field-set-street-address" type="text" placeholder="123 Main St" />
</div>
<div class="grid grid-cols-2 gap-4">
<div hlmField>
<label hlmFieldLabel for="field-set-city">City</label>
<input hlmInput id="field-set-city" type="text" placeholder="Los Angeles" />
</div>
<div hlmField>
<label hlmFieldLabel for="field-set-postal-code">Postal Code</label>
<input hlmInput id="field-set-postal-code" type="text" placeholder="90502" />
</div>
</div>
</div>
</fieldset>
`,
})
export class FieldSetPreview {}Checkbox
Your Desktop & Documents folders are being synced with iCloud Drive. You can access them from other devices.
import { Component } from '@angular/core';
import { HlmCheckboxImports } from '@spartan-ng/helm/checkbox';
import { HlmFieldImports } from '@spartan-ng/helm/field';
@Component({
selector: 'spartan-field-checkbox-preview',
imports: [HlmFieldImports, HlmCheckboxImports],
host: {
class: 'w-full max-w-md',
},
template: `
<div hlmFieldGroup>
<fieldset hlmFieldSet>
<legend hlmFieldLegend variant="label">Show these items on the desktop</legend>
<p hlmFieldDescription>Select the items you want to show on the desktop.</p>
<div hlmFieldGroup class="gap-3">
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-hard-disks" />
<label hlmFieldLabel for="field-hard-disks" class="font-normal">Hard disks</label>
</div>
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-external-disks" />
<label hlmFieldLabel for="field-external-disks" class="font-normal">External disks</label>
</div>
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-cds-dvds-ipods" />
<label hlmFieldLabel for="field-cds-dvds-ipods" class="font-normal">CDs, DVDs, and IPods</label>
</div>
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-connected-servers" />
<label hlmFieldLabel for="field-connected-servers" class="font-normal">Connected servers</label>
</div>
</div>
</fieldset>
<hlm-field-separator />
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-sync-desktop-documents" [checked]="true" />
<div hlmFieldContent>
<label hlmFieldLabel for="field-sync-desktop-documents">Sync Desktop & Documents folders</label>
<p hlmFieldDescription>
Your Desktop & Documents folders are being synced with iCloud Drive. You can access them from other devices.
</p>
</div>
</div>
</div>
`,
})
export class FieldCheckboxPreview {}Radio
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';
@Component({
selector: 'spartan-field-radio-preview',
imports: [HlmFieldImports, HlmRadioGroupImports],
host: {
class: 'w-full max-w-md',
},
template: `
<fieldset hlmFieldSet>
<label hlmFieldLabel>Subscription Plan</label>
<p hlmFieldDescription>Yearly and lifetime plans offer significant savings.</p>
<hlm-radio-group value="monthly">
<div hlmField orientation="horizontal">
<hlm-radio value="monthly" id="plan-monthly">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmFieldLabel for="plan-monthly" class="font-normal">Monthly ($9.99/month)</label>
</div>
<div hlmField orientation="horizontal">
<hlm-radio value="yearly" id="plan-yearly">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmFieldLabel for="plan-yearly" class="font-normal">Yearly ($99.99/year)</label>
</div>
<div hlmField orientation="horizontal">
<hlm-radio value="lifetime" id="plan-lifetime">
<hlm-radio-indicator indicator />
</hlm-radio>
<label hlmFieldLabel for="plan-lifetime" class="font-normal">Lifetime ($299.99/lifetime)</label>
</div>
</hlm-radio-group>
</fieldset>
`,
})
export class FieldRadioPreview {}Switch
Enable multi-factor authentication. If you do not have a two-factor device, you can use a one-time code sent to your email.
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmSwitchImports } from '@spartan-ng/helm/switch';
@Component({
selector: 'spartan-field-switch-preview',
imports: [HlmFieldImports, HlmSwitchImports],
host: {
class: 'w-full max-w-md',
},
template: `
<div hlmField orientation="horizontal">
<div hlmFieldContent>
<label hlmFieldLabel for="field-2fa">Multi-factor authentication</label>
<p hlmFieldDescription>
Enable multi-factor authentication. If you do not have a two-factor device, you can use a one-time code sent
to your email.
</p>
</div>
<hlm-switch id="field-2fa" />
</div>
`,
})
export class FieldSwitchPreview {}Choice Card
Wrap HlmField directives inside HlmFieldLabel to create selectable field groups. This works with RadioItem , Checkbox and Switch components.
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmRadioGroupImports } from '@spartan-ng/helm/radio-group';
@Component({
selector: 'spartan-field-choice-card-preview',
imports: [HlmFieldImports, HlmRadioGroupImports],
host: {
class: 'w-full max-w-md',
},
template: `
<div hlmFieldGroup>
<fieldset hlmFieldSet>
<label hlmFieldLabel>Compute Environment</label>
<p hlmFieldDescription>Select the compute environment for your cluster.</p>
<hlm-radio-group value="kubernetes">
<label hlmFieldLabel for="kubernetes">
<div hlmField orientation="horizontal">
<div hlmFieldContent>
<div hlmFieldTitle>Kubernetes</div>
<div hlmFieldDescription>Run GPU workloads on a K8s configured cluster.</div>
</div>
<hlm-radio value="kubernetes" id="kubernetes">
<hlm-radio-indicator indicator />
</hlm-radio>
</div>
</label>
<label hlmFieldLabel for="virtual-machine">
<div hlmField orientation="horizontal">
<div hlmFieldContent>
<div hlmFieldTitle>Virtual Machine</div>
<div hlmFieldDescription>Access a VM configured cluster to run GPU workloads.</div>
</div>
<hlm-radio value="virtual-machine" id="virtual-machine">
<hlm-radio-indicator indicator />
</hlm-radio>
</div>
</label>
</hlm-radio-group>
</fieldset>
</div>
`,
})
export class FieldChoiceCardPreview {}Field Group
Stack HlmField directives with HlmFieldGroup . Add HlmFieldSeparator to divide them.
import { Component } from '@angular/core';
import { HlmCheckboxImports } from '@spartan-ng/helm/checkbox';
import { HlmFieldImports } from '@spartan-ng/helm/field';
@Component({
selector: 'spartan-field-group-preview',
imports: [HlmFieldImports, HlmCheckboxImports],
host: {
class: 'w-full max-w-md',
},
template: `
<div hlmFieldGroup>
<fieldset hlmFieldSet>
<label hlmFieldLabel>Response</label>
<p hlmFieldDescription>
Get notified when ChatGPT responds to requests that take time, like research or image generation.
</p>
<div hlmFieldGroup data-slot="checkbox-group">
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-group-push-notifications" disabled [checked]="true" />
<label hlmFieldLabel for="field-group-push-notifications" class="font-normal">Push notifications</label>
</div>
</div>
</fieldset>
<hlm-field-separator />
<fieldset hlmFieldSet>
<label hlmFieldLabel>Tasks</label>
<p hlmFieldDescription>
Get notified when tasks you've created have updates.
<a href="#">Manage tasks</a>
</p>
<div hlmFieldGroup data-slot="checkbox-group">
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-group-push-task" />
<label hlmFieldLabel for="field-group-push-task" class="font-normal">Push notifications</label>
</div>
<div hlmField orientation="horizontal">
<hlm-checkbox id="field-group-email-task" />
<label hlmFieldLabel for="field-group-email-task" class="font-normal">Email notifications</label>
</div>
</div>
</fieldset>
</div>
`,
})
export class FieldGroupPreview {}Field Separator
Visual divider to separate sections inside a HlmFieldGroup . Accepts optional inline content.
Don't have an account? Sign up
import { Component } from '@angular/core';
import { RouterLink } from '@angular/router';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { remixGithubFill } from '@ng-icons/remixicon';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
@Component({
selector: 'spartan-field-separator-preview',
imports: [HlmFieldImports, HlmButtonImports, HlmInputImports, NgIcon, RouterLink],
providers: [provideIcons({ remixGithubFill })],
host: {
class: 'w-full max-w-xs',
},
template: `
<div hlmFieldGroup>
<div hlmField>
<label hlmFieldLabel for="field-separator-email">Email</label>
<input hlmInput id="field-separator-email" type="email" placeholder="m@example.com" />
</div>
<div hlmField>
<button hlmBtn type="submit">Login</button>
</div>
<hlm-field-separator>Or continue with</hlm-field-separator>
<div hlmField>
<button hlmBtn variant="outline" type="button">
<ng-icon name="remixGithubFill" class="text-xl" />
Login with GitHub
</button>
<p hlmFieldDescription class="text-center">
Don't have an account?
<a routerLink=".">Sign up</a>
</p>
</div>
</div>
`,
})
export class FieldSeparatorPreview {}Responsive Layout
- Vertical fields: Default orientation stacks label, control, and helper text—ideal for mobile-first layouts.
- Horizontal fields: Set
orientation="horizontal"onHlmFieldto align the label and control side-by-side. Pair withHlmFieldContentto keep descriptions aligned. - Responsive fields: Set
orientation="responsive"for automatic column layouts inside container-aware parents. Apply@container/field-groupclasses onHlmFieldGroupto switch orientations at specific breakpoints.
import { Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputImports } from '@spartan-ng/helm/input';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-field-responsive-layout-preview',
imports: [HlmFieldImports, HlmInputImports, HlmTextareaImports, HlmButtonImports],
host: {
class: 'w-full max-w-4xl',
},
template: `
<form>
<fieldset hlmFieldSet>
<legend hlmFieldLegend>Profile</legend>
<p hlmFieldDescription>Fill in your profile information.</p>
<hlm-field-separator />
<div hlmFieldGroup>
<div hlmField orientation="responsive">
<div hlmFieldContent>
<label hlmFieldLabel for="field-responsive-name">Name</label>
<p hlmFieldDescription>Provide your full name for identification</p>
</div>
<input hlmInput id="field-responsive-name" type="text" placeholder="Alex Cooper" />
</div>
<hlm-field-separator />
<div hlmField orientation="responsive">
<div hlmFieldContent>
<label hlmFieldLabel for="field-responsive-message">Message</label>
<p hlmFieldDescription>
You can write your message here. Keep it short, preferably under 100 characters.
</p>
</div>
<textarea
hlmTextarea
id="field-responsive-message"
placeholder="Hello, World!"
class="min-h-[100px] resize-none sm:min-w-[300px]"
></textarea>
</div>
<hlm-field-separator />
<div hlmField orientation="responsive">
<button hlmBtn type="submit">Submit</button>
<button hlmBtn type="button" variant="outline">Cancel</button>
</div>
</div>
</fieldset>
</form>
`,
})
export class FieldResponsiveLayoutPreview {}Validation and Errors
- Add
data-invalidtoHlmFieldto switch the entire block into an error state. - Add
aria-invalidon the input itself for assistive technologies. - Render
FieldErrorimmediately after the control or insideFieldContentto keep error messages aligned with the field.
<div hlmField data-invalid="true">
<label hlmFieldLabel for="validation-error-email">Email</label>
<input hlmInput id="validation-error-email" type="email" aria-invalid="true" />
<hlm-field-error>Enter a valid email address.</hlm-field-error>
</div>Accessibility
HlmFieldSetandHlmFieldLegendkeep related controls grouped for keyboard and assistive tech users.HlmFieldoutputsrole="group"so nested controls inherit labeling fromHlmFieldLabelandHlmFieldLegendwhen combined.- Apply
HlmFieldSeparatorsparingly to ensure screen readers encounter clear section boundaries.
Helm API
HlmFieldContent
Selector: [hlmFieldContent],hlm-field-content
HlmFieldDescription
Selector: [hlmFieldDescription],hlm-field-description
HlmFieldError
Selector: hlm-field-error
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| class | ClassValue | - | - |
| error | Array<{ message: string } | undefined> | - | - |
HlmFieldGroup
Selector: [hlmFieldGroup],hlm-field-group
HlmFieldLabel
Selector: [hlmFieldLabel],hlm-field-label
HlmFieldLegend
Selector: legend[hlmFieldLegend]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| variant | 'label' | 'legend' | legend | - |
HlmFieldSeparator
Selector: hlm-field-separator
HlmFieldSet
Selector: fieldset[hlmFieldSet]
HlmFieldTitle
Selector: [hlmFieldTitle],hlm-field-title
HlmField
Selector: [hlmField],hlm-field
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| orientation | FieldVariants['orientation'] | vertical | - |
On This Page