- 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
Input OTP
Accessible one-time password component.
import { Component } from '@angular/core';
import { BrnInputOtp } from '@spartan-ng/brain/input-otp';
import { HlmInputOtp, HlmInputOtpGroup, HlmInputOtpSeparator, HlmInputOtpSlot } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-preview',
imports: [HlmInputOtp, HlmInputOtpGroup, HlmInputOtpSeparator, HlmInputOtpSlot, BrnInputOtp],
template: `
<brn-input-otp hlmInputOtp maxLength="6" inputClass="disabled:cursor-not-allowed">
<div hlmInputOtpGroup>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</div>
<hlm-input-otp-separator />
<div hlmInputOtpGroup>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</div>
</brn-input-otp>
`,
})
export class InputOtpPreview {}Installation
ng g @spartan-ng/cli:ui input-otpnx g @spartan-ng/cli:ui input-otpimport { 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, { NumberInput } from '@angular/cdk/coercion';
import { BrnInputOtpSlot } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, input, numberAttribute } from '@angular/core';
import { HlmIcon } from '@spartan-ng/helm/icon';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
@Component({
selector: 'hlm-input-otp-fake-caret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="pointer-events-none absolute inset-0 flex items-center justify-center">
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
</div>
`,
})
export class HlmInputOtpFakeCaret {}
@Directive({
selector: '[hlmInputOtpGroup]',
host: {
'data-slot': 'input-otp-group',
},
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
imports: [HlmIcon, NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon hlm name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => 'inline-flex');
}
}
@Component({
selector: 'hlm-input-otp-slot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'data-slot': 'input-otp-slot',
},
template: `
<brn-input-otp-slot [index]="index()">
<hlm-input-otp-fake-caret />
</brn-input-otp-slot>
`,
})
export class HlmInputOtpSlot {
/** The index of the slot to render the char or a fake caret */
public readonly index = input.required<number, NumberInput>({ transform: numberAttribute });
constructor() {
classes(() => [
'dark:bg-input/30 border-input relative flex h-9 w-9 items-center justify-center border-y border-r text-sm shadow-xs transition-all outline-none first:rounded-l-md first:border-l last:rounded-r-md',
'has-[brn-input-otp-slot[data-active="true"]]:border-ring has-[brn-input-otp-slot[data-active="true"]]:ring-ring/50 has-[brn-input-otp-slot[data-active="true"]]:z-10 has-[brn-input-otp-slot[data-active="true"]]:ring-[3px]',
]);
}
}
@Directive({
selector: 'brn-input-otp[hlmInputOtp], brn-input-otp[hlm]',
host: {
'data-slot': 'input-otp',
},
})
export class HlmInputOtp {
constructor() {
classes(() => 'flex items-center gap-2 has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;Usage
import { BrnInputOtp } from '@spartan-ng/brain/input-otp';
import {
HlmInputOtp
HlmInputOtpGroup
HlmInputOtpSeparator
HlmInputOtpSlot
} from '@spartan-ng/helm/input-otp';<brn-input-otp hlmInputOtp maxLength="6" inputClass="disabled:cursor-not-allowed">
<div hlmInputOtpGroup>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</div>
<hlm-input-otp-separator />
<div hlmInputOtpGroup>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</div>
</brn-input-otp>Animation
The fake caret animation animate-caret-blink is provided by tw-animate-css , which is included in @spartan-ng/brain/hlm-tailwind-preset.css . Here are three options for adding the animation to your project.
/* 1. default import includes 'tw-animate-css' */
@import '@spartan-ng/brain/hlm-tailwind-preset.css';
/* 2. import 'tw-animate-css' direclty */
@import 'tw-animate-css';
/* 3. add animate-caret-blink animation from 'tw-animate-css' */
@theme inline {
--animate-caret-blink: caret-blink 1.25s ease-out infinite;
@keyframes caret-blink {
0%,
70%,
100% {
opacity: 1;
}
20%,
50% {
opacity: 0;
}
}
} Adjust the animation to your needs by changing duration, easing function or keyframes by overriding the CSS variable --animate-caret-blink or the @keyframes caret-blink in your global styles.
@import '@spartan-ng/brain/hlm-tailwind-preset.css';
/* adjust animation duration */
@theme inline {
- --animate-caret-blink: caret-blink 1.25s ease-out infinite;
+ --animate-caret-blink: caret-blink 2s ease-out infinite;
}Examples
Form
Sync the otp to a form by adding formControlName to brn-input-otp .
import { afterNextRender, Component, computed, inject, type OnDestroy, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { BrnInputOtp } from '@spartan-ng/brain/input-otp';
import { toast } from '@spartan-ng/brain/sonner';
import { HlmButton } from '@spartan-ng/helm/button';
import { HlmInputOtp, HlmInputOtpGroup, HlmInputOtpSlot } from '@spartan-ng/helm/input-otp';
import { HlmToaster } from '@spartan-ng/helm/sonner';
@Component({
selector: 'spartan-input-otp-form',
imports: [ReactiveFormsModule, HlmButton, HlmToaster, BrnInputOtp, HlmInputOtp, HlmInputOtpGroup, HlmInputOtpSlot],
host: {
class: 'preview flex min-h-[350px] w-full justify-center p-10 items-center',
},
template: `
<hlm-toaster />
<form [formGroup]="form" (ngSubmit)="submit()" class="space-y-8">
<brn-input-otp
hlmInputOtp
[maxLength]="maxLength"
inputClass="disabled:cursor-not-allowed"
formControlName="otp"
[transformPaste]="transformPaste"
(completed)="submit()"
>
<div hlmInputOtpGroup>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</div>
</brn-input-otp>
<div class="flex flex-col gap-4">
<button type="submit" hlmBtn [disabled]="form.invalid">Submit</button>
<button type="button" hlmBtn variant="ghost" [disabled]="isResendDisabled()" (click)="resendOtp()">
Resend in {{ countdown() }}s
</button>
</div>
</form>
`,
})
export class InputOtpFormExample implements OnDestroy {
private readonly _formBuilder = inject(FormBuilder);
private _intervalId?: NodeJS.Timeout;
public readonly countdown = signal(60);
public readonly isResendDisabled = computed(() => this.countdown() > 0);
public maxLength = 6;
/** Overrides global formatDate */
public transformPaste = (pastedText: string) => pastedText.replaceAll('-', '');
public form = this._formBuilder.group({
otp: [null, [Validators.required, Validators.minLength(this.maxLength), Validators.maxLength(this.maxLength)]],
});
constructor() {
afterNextRender(() => this.startCountdown());
}
submit() {
console.log(this.form.value);
toast('OTP submitted', {
description: `Your OTP ${this.form.value.otp} has been submitted`,
});
}
resendOtp() {
// add your api request here to resend OTP
this.resetCountdown();
}
ngOnDestroy() {
this.stopCountdown();
}
private resetCountdown() {
this.countdown.set(60);
this.startCountdown();
}
private startCountdown() {
this.stopCountdown();
this._intervalId = setInterval(() => {
this.countdown.update((countdown) => Math.max(0, countdown - 1));
if (this.countdown() === 0) {
this.stopCountdown();
}
}, 1000);
}
private stopCountdown() {
if (this._intervalId) {
clearInterval(this._intervalId);
this._intervalId = undefined;
}
}
}Brain API
BrnInputOtpSlot
Selector: brn-input-otp-slot
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| index* (required) | number | - | The index of the slot to render the char or a fake caret |
BrnInputOtp
Selector: brn-input-otp
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| hostStyles | string | position: relative; cursor: text; user-select: none; pointer-events: none; | Styles applied to the host element. |
| inputId | string | `brn-input-otp-${++BrnInputOtp._id}` | Custom id applied to the input element |
| inputAutocomplete | 'one-time-code' | 'off' | one-time-code | Custom autocomplete attribute applied to the input element |
| inputStyles | string | position: absolute; inset: 0; width: 100%; height: 100%; display: flex; textAlign: left; opacity: 1; color: transparent; pointerEvents: all; background: transparent; caret-color: transparent; border: 0px solid transparent; outline: transparent solid 0px; box-shadow: none; line-height: 1; letter-spacing: -0.5em; font-family: monospace; font-variant-numeric: tabular-nums; | Styles applied to the input element to make it invisible and clickable. |
| containerStyles | string | position: absolute; inset: 0; pointer-events: none; | Styles applied to the container element. |
| disabled | boolean | false | Determine if the date picker is disabled. |
| maxLength* (required) | number | - | The number of slots. |
| inputMode | InputMode | numeric | Virtual keyboard appearance on mobile |
| inputClass | ClassValue | - | - |
| autofocus | boolean | false | If true, the element is focused automatically on init * |
| transformPaste | (pastedText: string, maxLength: number) => string | (text) => text | Defines how the pasted text should be transformed before saving to model/form. Allows pasting text which contains extra characters like spaces, dashes, etc. and are longer than the maxLength. "XXX-XXX": (pastedText) => pastedText.replaceAll('-', '') "XXX XXX": (pastedText) => pastedText.replaceAll(/\s+/g, '') |
| value | string | null | null | The value controlling the input |
Outputs
| Prop | Type | Default | Description |
|---|---|---|---|
| valueChange | string | - | Emits when the value changes. |
| completed | string | - | Emitted when the input is complete, triggered through input or paste. |
Helm API
HlmInputOtpFakeCaret
Selector: hlm-input-otp-fake-caret
HlmInputOtpGroup
Selector: [hlmInputOtpGroup]
HlmInputOtpSeparator
Selector: hlm-input-otp-separator
HlmInputOtpSlot
Selector: hlm-input-otp-slot
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| index* (required) | number | - | The index of the slot to render the char or a fake caret |
HlmInputOtp
Selector: brn-input-otp[hlmInputOtp], brn-input-otp[hlm]
On This Page