- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Attachment
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Bubble
- Button
- Button Group
- Calendar
- Card
- Carousel
- Chart
- Checkbox
- Code Block
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Marker
- Menubar
- Message
- Message Scroller
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Questionnaire
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner (Toast)
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toggle
- Toggle Group
- Tooltip
- Trace
Input OTP
Accessible one-time password component.
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-preview',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-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, NgZone, PLATFORM_ID, effect, inject, makeEnvironmentProviders, runInInjectionContext, type EnvironmentProviders } from '@angular/core';
import { OVERLAY_DEFAULT_CONFIG } from '@angular/cdk/overlay';
import { clsx, type ClassValue } from 'clsx';
import { isPlatformBrowser } from '@angular/common';
import { provideSpartanHlm } from '@spartan-ng/helm/utils';
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. Created outside the zone so
// class mutations don't trigger app-wide change detection (and loop if CD writes a class).
inject(NgZone).runOutsideAngular(() => 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;
}
/**
* Provides default configuration for Spartan Helm components.
*
* This utility configures the Angular CDK overlay to disable the `usePopover`
* behavior introduced in Angular 21, which causes CDK overlay-based components
* (sheets, dialogs, tooltips, etc.) to render above `position: fixed` elements
* like `<hlm-toaster>`.
*
* @returns {EnvironmentProviders} Environment providers to be added to the application config.
*
* @example
* ```ts
* // app.config.ts
*
*
* export const appConfig: ApplicationConfig = {
* providers: [
* provideSpartanHlm(),
* // ... other providers
* ],
* };
* ```
*/
export function provideSpartanHlm(): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: OVERLAY_DEFAULT_CONFIG,
useValue: { usePopover: false },
},
]);
}import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-lg has-data-[matches-spartan-invalid=true]:ring-3 flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'dark:bg-input/30 border-input 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"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:border-destructive size-8 border-y border-e text-sm transition-all outline-none first:rounded-s-lg first:border-s last:rounded-e-lg has-[brn-input-otp-slot[data-active="true"]]:ring-3 relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-md has-data-[matches-spartan-invalid=true]:ring-3 flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'dark:bg-input/30 border-input 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"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:border-destructive size-9 border-y border-e text-sm shadow-xs transition-all outline-none first:rounded-s-md first:border-s last:rounded-e-md has-[brn-input-otp-slot[data-active="true"]]:ring-3 relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-none has-data-[matches-spartan-invalid=true]:ring-1 flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'dark:bg-input/30 border-input 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"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:border-destructive size-8 border-y border-e text-xs transition-all outline-none first:rounded-none first:border-s last:rounded-none has-[brn-input-otp-slot[data-active="true"]]:ring-1 relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-4xl has-data-[matches-spartan-invalid=true]:ring-[3px] flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'bg-input/30 border-input 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"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:border-destructive size-9 border-y border-e text-sm transition-all outline-none first:rounded-s-4xl first:border-s last:rounded-e-4xl has-[brn-input-otp-slot[data-active="true"]]:ring-[3px] relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-md has-data-[matches-spartan-invalid=true]:ring-2 flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'bg-input/20 dark:bg-input/30 border-input has-[brn-input-otp-slot[data-active="true"]]:border-ring has-[brn-input-otp-slot[data-active="true"]]:ring-ring/30 has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:border-destructive size-7 border-y border-e text-xs/relaxed transition-all outline-none first:rounded-s-md first:border-s last:rounded-e-md has-[brn-input-otp-slot[data-active="true"]]:ring-2 relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;import { BrnInputOtp, BrnInputOtpInput, BrnInputOtpSlot, type InputMode } from '@spartan-ng/brain/input-otp';
import { ChangeDetectionStrategy, Component, Directive, booleanAttribute, computed, input, numberAttribute } from '@angular/core';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { classes, hlm } from '@spartan-ng/helm/utils';
import { lucideMinus } from '@ng-icons/lucide';
import { type BooleanInput, type NumberInput } from '@angular/cdk/coercion';
import { type ClassValue } from 'clsx';
@Component({
selector: 'hlm-input-otp-fake-caret',
exportAs: 'hlmInputOtpFakeCaret',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="animate-caret-blink bg-foreground h-4 w-px duration-1000"></div>
`,
})
export class HlmInputOtpFakeCaret {
constructor() {
classes(() => 'pointer-events-none absolute inset-0 flex items-center justify-center');
}
}
@Directive({
selector: '[hlmInputOtpGroup],hlm-input-otp-group',
exportAs: 'hlmInputOtpGroup',
host: { 'data-slot': 'input-otp-group' },
})
export class HlmInputOtpGroup {
constructor() {
classes(() => 'has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive rounded-3xl has-data-[matches-spartan-invalid=true]:ring-3 flex items-center');
}
}
@Component({
selector: 'hlm-input-otp-separator',
exportAs: 'hlmInputOtpSeparator',
imports: [NgIcon],
providers: [provideIcons({ lucideMinus })],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
role: 'separator',
'data-slot': 'input-otp-separator',
},
template: `
<ng-icon name="lucideMinus" />
`,
})
export class HlmInputOtpSeparator {
constructor() {
classes(() => "[&_ng-icon:not([class*='text-'])]:text-[length:--spacing(4)] flex items-center");
}
}
@Component({
selector: 'hlm-input-otp-slot',
exportAs: 'hlmInputOtpSlot',
imports: [BrnInputOtpSlot, HlmInputOtpFakeCaret],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { 'data-slot': 'input-otp-slot' },
template: `
<brn-input-otp-slot [index]="index()" [forceInvalid]="forceInvalid()">
<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 });
/** Whether to force the input into an invalid state. */
public readonly forceInvalid = input<boolean, BooleanInput>(false, { transform: booleanAttribute });
constructor() {
classes(
() =>
'bg-input/50 border-input has-[brn-input-otp-slot[data-active="true"]]:border-ring has-[brn-input-otp-slot[data-active="true"]]:ring-ring/30 has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/20 dark:has-[brn-input-otp-slot[data-active="true"]]:has-data-[matches-spartan-invalid=true]:ring-destructive/40 has-data-[matches-spartan-invalid=true]:border-destructive size-9 border-y border-e text-sm transition-all outline-none first:rounded-s-3xl first:border-s last:rounded-e-3xl has-[brn-input-otp-slot[data-active="true"]]:ring-3 relative flex items-center justify-center has-[brn-input-otp-slot[data-active="true"]]:z-10',
);
}
}
@Component({
selector: 'hlm-input-otp',
exportAs: 'hlmInputOtp',
imports: [BrnInputOtpInput],
changeDetection: ChangeDetectionStrategy.OnPush,
hostDirectives: [
{
directive: BrnInputOtp,
inputs: [
'length',
'value',
'disabled',
'inputId',
'hostStyles',
'autofocus',
'transformPaste',
'mask',
'maskChar',
'slotPattern',
],
outputs: ['valueChange', 'completed'],
},
],
host: { 'data-slot': 'input-otp' },
template: `
<ng-content />
<input
brnInputOtpInput
[autocomplete]="inputAutocomplete()"
[inputMode]="inputMode()"
[class]="_inputClass()"
[inputStyles]="inputStyles()"
/>
`,
})
export class HlmInputOtp {
/** Custom autocomplete attribute applied to the input element */
public readonly inputAutocomplete = input<'one-time-code' | 'off'>('one-time-code');
/** Virtual keyboard appearance on mobile */
public readonly inputMode = input<InputMode>('numeric');
/** Classes applied to the input element. */
public readonly inputClass = input<ClassValue>('');
/** Overrides the default styles applied to the input element. */
public readonly inputStyles = input<string | undefined>(undefined);
protected readonly _inputClass = computed(() => hlm('disabled:cursor-not-allowed', this.inputClass()));
constructor() {
classes(() => 'gap-2 flex items-center has-disabled:opacity-50');
}
}
export const HlmInputOtpImports = [
HlmInputOtp,
HlmInputOtpGroup,
HlmInputOtpSeparator,
HlmInputOtpSlot,
HlmInputOtpFakeCaret,
] as const;Usage
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';<hlm-input-otp length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-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
Pattern
Use the slotPattern prop to restrict the characters that can be entered. The example below only accepts digits.
import { Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-pattern',
imports: [HlmFieldImports, HlmInputOtpImports],
template: `
<hlm-field class="mx-auto max-w-xs">
<label hlmFieldLabel for="input-otp-pattern">Digit only</label>
<hlm-input-otp inputId="input-otp-pattern" slotPattern="[0-9]" length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
</hlm-field>
`,
})
export class InputOtpPattern {}Separator
Use the hlm-input-otp-separator component to add a separator between input groups.
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-separator',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="2" />
<hlm-input-otp-slot index="3" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
`,
})
export class InputOtpSeparator {}Disabled
Use the disabled prop to disable the input.
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-disabled',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp value="123456" disabled length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
`,
})
export class InputOtpDisabled {}Invalid
Use the forceInvalid prop to mark the slots as invalid.
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-invalid',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" forceInvalid />
<hlm-input-otp-slot index="1" forceInvalid />
<hlm-input-otp-slot index="2" forceInvalid />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" forceInvalid />
<hlm-input-otp-slot index="4" forceInvalid />
<hlm-input-otp-slot index="5" forceInvalid />
</hlm-input-otp-group>
</hlm-input-otp>
`,
})
export class InputOtpInvalid {}Four Digits
A common pattern for PIN codes. Use slotPattern="[0-9]" and length="4" .
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-four-digits',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp slotPattern="[0-9]" length="4">
<hlm-input-otp-group>
<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-group>
</hlm-input-otp>
`,
})
export class InputOtpFourDigits {}Alphanumeric
Use slotPattern="[A-Za-z0-9]" to accept both letters and numbers.
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-alphanumeric',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp slotPattern="[A-Za-z0-9]" inputMode="text" length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
`,
})
export class InputOtpAlphanumeric {}Masked
Use the mask prop to visually obscure entered characters. The form value remains unmasked. Customize the mask character with maskChar .
import { Component } from '@angular/core';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-masked',
imports: [HlmInputOtpImports],
template: `
<hlm-input-otp mask length="6">
<hlm-input-otp-group>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
`,
})
export class InputOtpMasked {}Form
Sync the OTP to an Angular Signal Form by binding [formField] to hlm-input-otp .
import { afterNextRender, Component, computed, type OnDestroy, signal } from '@angular/core';
import { form, FormField, FormRoot, maxLength, minLength, required, submit } from '@angular/forms/signals';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideRefreshCw } from '@ng-icons/lucide';
import { toast } from '@spartan-ng/brain/sonner';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmCardImports } from '@spartan-ng/helm/card';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
import { HlmToasterImports } from '@spartan-ng/helm/sonner';
@Component({
selector: 'spartan-input-otp-form',
imports: [
FormRoot,
FormField,
NgIcon,
HlmButtonImports,
HlmToasterImports,
HlmCardImports,
HlmFieldImports,
HlmInputOtpImports,
],
providers: [provideIcons({ lucideRefreshCw })],
host: {
class: 'preview flex min-h-[350px] w-full justify-center items-center max-w-lg',
},
template: `
<hlm-toaster />
<hlm-card class="mx-auto">
<hlm-card-header>
<div hlmCardTitle>Verify your login</div>
<div hlmCardDescription>
Enter the verification code we sent to your email address:
<span class="font-medium">m@example.com</span>
.
</div>
</hlm-card-header>
<form hlmCardContent id="otp-form" [formRoot]="form">
<hlm-field>
<div class="flex items-center justify-between">
<label hlmFieldLabel>Verification code</label>
<button hlmBtn variant="outline" size="xs" [disabled]="isResendDisabled()" (click)="resendOtp()">
<ng-icon name="lucideRefreshCw" />
Resend code
@if (countdown() > 0) {
in {{ countdown() }}s
}
</button>
</div>
<hlm-input-otp
[length]="maxLength"
inputId="otp-verification"
[formField]="form.otp"
[transformPaste]="transformPaste"
(completed)="submit()"
>
<hlm-input-otp-group
class="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl"
>
<hlm-input-otp-slot index="0" />
<hlm-input-otp-slot index="1" />
<hlm-input-otp-slot index="2" />
</hlm-input-otp-group>
<hlm-input-otp-separator />
<hlm-input-otp-group
class="*:data-[slot=input-otp-slot]:h-12 *:data-[slot=input-otp-slot]:w-11 *:data-[slot=input-otp-slot]:text-xl"
>
<hlm-input-otp-slot index="3" />
<hlm-input-otp-slot index="4" />
<hlm-input-otp-slot index="5" />
</hlm-input-otp-group>
</hlm-input-otp>
<hlm-field-description>
<a href="#">I no longer have access to this email address.</a>
</hlm-field-description>
</hlm-field>
</form>
<hlm-card-footer>
<hlm-field>
<button type="submit" form="otp-form" hlmBtn [disabled]="form().invalid()">Verify</button>
<div class="text-muted-foreground text-sm">
Having trouble signing in?
<a href="#" class="hover:text-primary underline underline-offset-4 transition-colors">Contact support</a>
</div>
</hlm-field>
</hlm-card-footer>
</hlm-card>
`,
})
export class InputOtpFormExample implements OnDestroy {
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('-', '');
private readonly _model = signal({
otp: '',
});
public readonly form = form(
this._model,
(schemaPath) => {
required(schemaPath.otp, { message: 'OTP is required' });
minLength(schemaPath.otp, this.maxLength, { message: `OTP must be ${this.maxLength} characters` });
maxLength(schemaPath.otp, this.maxLength, { message: `OTP must be ${this.maxLength} characters` });
},
{
submission: {
action: async () => {
const model = this._model();
console.log(model);
toast('OTP submitted', {
description: `Your OTP ${model.otp} has been submitted`,
});
},
},
},
);
constructor() {
afterNextRender(() => this.startCountdown());
}
submit() {
submit(this.form);
}
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;
}
}
}RTL
To enable RTL support in spartan-ng, see the RTL configuration guide.
import { Component, computed, inject } from '@angular/core';
import { TranslateService, Translations } from '@spartan-ng/app/app/shared/translate.service';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmInputOtpImports } from '@spartan-ng/helm/input-otp';
@Component({
selector: 'spartan-input-otp-rtl',
imports: [HlmFieldImports, HlmInputOtpImports],
template: `
<hlm-field class="mx-auto max-w-xs" [dir]="_dir()">
<label hlmFieldLabel for="input-otp-rtl">{{ _t()['verificationCode'] }}</label>
<hlm-input-otp inputId="input-otp-rtl" value="123456" length="6">
<hlm-input-otp-group>
<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" />
</hlm-input-otp-group>
</hlm-input-otp>
</hlm-field>
`,
})
export class InputOtpRtl {
private readonly _language = inject(TranslateService).language;
private readonly _translations: Translations = {
en: {
dir: 'ltr',
values: {
verificationCode: 'Verification code',
},
},
ar: {
dir: 'rtl',
values: {
verificationCode: 'رمز التحقق',
},
},
he: {
dir: 'rtl',
values: {
verificationCode: 'קוד אימות',
},
},
};
private readonly _translation = computed(() => this._translations[this._language()]);
protected readonly _t = computed(() => this._translation().values);
protected readonly _dir = computed(() => this._translation().dir);
}Brain API
BrnInputOtpInput
Selector: input[brnInputOtpInput]
ExportAs: brnInputOtpInput
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| autocomplete | 'one-time-code' | 'off' | 'one-time-code' | Custom autocomplete attribute applied to the input element |
| inputMode | InputMode | 'numeric' | Virtual keyboard appearance on mobile |
| inputStyles | string | undefined | undefined | Styles applied to the input element to make it invisible and clickable. |
BrnInputOtpSlot
Selector: brn-input-otp-slot
ExportAs: brnInputOtpSlot
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| index* (required) | number | - | The index of the slot to render the char or a fake caret |
| forceInvalid | boolean | false | Whether to force the input into an invalid state. |
BrnInputOtp
Selector: brn-input-otp, [brnInputOtp]
ExportAs: brnInputOtp
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 |
| disabled | boolean | false | Determine if the input is disabled. |
| length* (required) | number | - | The number of slots. |
| slotPattern | string | RegExp | null | null | Optional per-character pattern. Each typed or pasted character must match this pattern. Strings are treated as a single-character regular expression. Examples: '[0-9]', '[A-Za-z0-9]' |
| mask | boolean | false | Whether entered characters should be visually masked. |
| maskChar | string | '•' | The character used to mask entered characters. |
| autofocus | boolean | false | If true, the element is focused automatically on init * |
| transformPaste | (pastedText: string, length: 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 length. "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
ExportAs: hlmInputOtpFakeCaret
HlmInputOtpGroup
Selector: [hlmInputOtpGroup],hlm-input-otp-group
ExportAs: hlmInputOtpGroup
HlmInputOtpSeparator
Selector: hlm-input-otp-separator
ExportAs: hlmInputOtpSeparator
HlmInputOtpSlot
Selector: hlm-input-otp-slot
ExportAs: hlmInputOtpSlot
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| index* (required) | number | - | The index of the slot to render the char or a fake caret |
| forceInvalid | boolean | false | Whether to force the input into an invalid state. |
HlmInputOtp
Selector: hlm-input-otp
ExportAs: hlmInputOtp
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| inputAutocomplete | 'one-time-code' | 'off' | 'one-time-code' | Custom autocomplete attribute applied to the input element |
| inputMode | InputMode | 'numeric' | Virtual keyboard appearance on mobile |
| inputClass | ClassValue | '' | Classes applied to the input element. |
| inputStyles | string | undefined | undefined | Overrides the default styles applied to the input element. |
| length* (required) | number | - | The number of slots. |
| value | string | null | null | The value controlling the input |
| disabled | boolean | false | Determine if the input is disabled. |
| inputId | string | `brn-input-otp-${++BrnInputOtp._id}` | Custom id applied to the input element |
| hostStyles | string | 'position: relative; cursor: text; user-select: none; pointer-events: none;' | Styles applied to the host element. |
| autofocus | boolean | false | If true, the element is focused automatically on init * |
| transformPaste | (pastedText: string, length: 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 length. "XXX-XXX": (pastedText) => pastedText.replaceAll('-', '') "XXX XXX": (pastedText) => pastedText.replaceAll(/\s+/g, '') |
| mask | boolean | false | Whether entered characters should be visually masked. |
| maskChar | string | '•' | The character used to mask entered characters. |
| slotPattern | string | RegExp | null | null | Optional per-character pattern. Each typed or pasted character must match this pattern. Strings are treated as a single-character regular expression. Examples: '[0-9]', '[A-Za-z0-9]' |
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. |
On This Page