Getting Started
UI
Components
- Accordion
- Alert
- Alert Dialog
- Aspect Ratio
- Autocomplete
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Calendar
- Card
- Carousel
- Checkbox
- Collapsible
- Combobox
- Command
- Context Menu
- Data Table
- Date Picker
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Icon
- Input Group
- Input OTP
- Input
- Item
- Kbd
- Label
- Menubar
- Native Select
- Navigation Menu
- Pagination
- Popover
- Progress
- Radio Group
- Resizable
- Scroll Area
- Select
- Separator
- Sheet
- Sidebar
- Skeleton
- Slider
- Sonner (Toast)
- Spinner
- Switch
- Table
- Tabs
- Textarea
- Toggle
- Toggle Group
- Tooltip
Forms
Stack
Textarea
Displays a form textarea or a component that looks like a textarea.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-preview',
imports: [HlmTextareaImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<textarea hlmTextarea placeholder="Type your message here."></textarea>
`,
})
export class TextareaPreview {}Installation
ng g @spartan-ng/cli:ui textareanx g @spartan-ng/cli:ui textareaimport { 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 { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'border-input dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 rounded-md border bg-transparent px-2.5 py-2 text-base shadow-xs transition-[color,box-shadow] focus-visible:ring-3 data-[matches-spartan-invalid=true]:ring-3 md:text-sm placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'border-input dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 disabled:bg-input/50 dark:disabled:bg-input/80 rounded-none border bg-transparent px-2.5 py-2 text-xs transition-colors focus-visible:ring-1 data-[matches-spartan-invalid=true]:ring-1 md:text-xs placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'border-input bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 resize-none rounded-xl border px-3 py-3 text-base transition-colors focus-visible:ring-3 data-[matches-spartan-invalid=true]:ring-3 md:text-sm placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'border-input bg-input/20 dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/30 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 resize-none rounded-md border px-2 py-2 text-sm transition-colors focus-visible:ring-2 data-[matches-spartan-invalid=true]:ring-2 md:text-xs/relaxed placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'border-input dark:bg-input/30 focus-visible:border-ring focus-visible:ring-ring/50 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 disabled:bg-input/50 dark:disabled:bg-input/80 rounded-lg border bg-transparent px-2.5 py-2 text-base transition-colors focus-visible:ring-3 data-[matches-spartan-invalid=true]:ring-3 md:text-sm placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;import { BrnFieldControlDescribedBy } from '@spartan-ng/brain/field';
import { BrnTextarea } from '@spartan-ng/brain/textarea';
import { Directive } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
@Directive({
selector: '[hlmTextarea]',
hostDirectives: [{ directive: BrnTextarea, inputs: ['id', 'forceInvalid'] }, BrnFieldControlDescribedBy],
host: { 'data-slot': 'textarea' },
})
export class HlmTextarea {
constructor() {
classes(
() =>
'bg-input/50 focus-visible:border-ring focus-visible:ring-ring/30 data-[matches-spartan-invalid=true]:ring-destructive/20 dark:data-[matches-spartan-invalid=true]:ring-destructive/40 data-[matches-spartan-invalid=true]:border-destructive dark:data-[matches-spartan-invalid=true]:border-destructive/50 resize-none rounded-2xl border border-transparent px-3 py-3 text-base transition-[color,box-shadow,background-color] focus-visible:ring-3 data-[matches-spartan-invalid=true]:ring-3 md:text-sm placeholder:text-muted-foreground flex field-sizing-content min-h-16 w-full outline-none disabled:cursor-not-allowed disabled:opacity-50',
);
}
}
export const HlmTextareaImports = [HlmTextarea] as const;Usage
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';<textarea hlmTextarea placeholder="Type your message here."></textarea>Examples
Field
Use hlm-field , hlmFieldLabel , and hlm-field-description to create a textarea with a label and description.
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-field',
imports: [HlmTextareaImports, HlmFieldImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<hlm-field>
<label hlmFieldLabel for="textarea-message">Message</label>
<hlm-field-description>Enter your message below.</hlm-field-description>
<textarea hlmTextarea id="textarea-message" placeholder="Type your message here."></textarea>
</hlm-field>
`,
})
export class TextareaField {}Disabled
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-disabled',
imports: [HlmTextareaImports, HlmFieldImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<hlm-field data-disabled="true">
<label hlmFieldLabel for="textarea-disabled">Message</label>
<textarea hlmTextarea id="textarea-disabled" placeholder="Type your message here." disabled></textarea>
</hlm-field>
`,
})
export class TextareaDisabledPreview {}Invalid
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-invalid',
imports: [HlmTextareaImports, HlmFieldImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<hlm-field forceInvalid>
<label hlmFieldLabel for="textarea-invalid">Message</label>
<textarea hlmTextarea forceInvalid id="textarea-invalid" placeholder="Type your message here."></textarea>
<hlm-field-description>Please enter a valid message.</hlm-field-description>
</hlm-field>
`,
})
export class TextareaInvalid {}Button
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-button',
imports: [HlmTextareaImports, HlmButtonImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<div class="grid w-full gap-2">
<textarea hlmTextarea placeholder="Type your message here."></textarea>
<button hlmBtn>Send message</button>
</div>
`,
})
export class TextareaButtonPreview {}Form
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmFieldImports } from '@spartan-ng/helm/field';
import { HlmLabelImports } from '@spartan-ng/helm/label';
import { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-form',
imports: [HlmTextareaImports, HlmLabelImports, HlmButtonImports, HlmFieldImports, ReactiveFormsModule],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'min-w-sm',
},
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<hlm-field-group>
<hlm-field>
<label hlmFieldLabel for="username">Bio</label>
<textarea
hlmTextarea
class="w-80"
id="username"
placeholder="Tell us a little bit about yourself"
formControlName="bio"
></textarea>
<p hlmFieldDescription>
You can
<span>@mention</span>
other users and organizations.
</p>
</hlm-field>
<hlm-field orientation="horizontal">
<button hlmBtn type="submit">Submit</button>
</hlm-field>
</hlm-field-group>
</form>
`,
})
export class TextareaFormPreview {
private readonly _formBuilder = inject(FormBuilder);
public form = this._formBuilder.group({
bio: [null, Validators.required],
});
submit() {
console.log(this.form.value);
}
}RTL
To enable RTL support in spartan-ng, see the RTL configuration guide.
import { ChangeDetectionStrategy, 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 { HlmTextareaImports } from '@spartan-ng/helm/textarea';
@Component({
selector: 'spartan-textarea-rtl',
imports: [HlmTextareaImports, HlmFieldImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: 'min-w-sm' },
template: `
<hlm-field [dir]="_dir()">
<label hlmFieldLabel for="textarea-message">{{ _t()['label'] }}</label>
<textarea hlmTextarea id="textarea-message" [placeholder]="_t()['placeholder']"></textarea>
<hlm-field-description>{{ _t()['description'] }}</hlm-field-description>
</hlm-field>
`,
})
export class TextareaRtl {
private readonly _language = inject(TranslateService).language;
private readonly _translations: Translations = {
en: {
dir: 'ltr',
values: {
label: 'Feedback',
placeholder: 'Your feedback helps us improve...',
description: 'Share your thoughts about our service.',
},
},
ar: {
dir: 'rtl',
values: {
label: 'التعليقات',
placeholder: 'تعليقاتك تساعدنا على التحسين...',
description: 'شاركنا أفكارك حول خدمتنا.',
},
},
he: {
dir: 'rtl',
values: {
label: 'משוב',
placeholder: 'המשוב שלך עוזר לנו להשתפר...',
description: 'שתף את מחשבותיך על השירות שלנו.',
},
},
};
private readonly _translation = computed(() => this._translations[this._language()]);
protected readonly _t = computed(() => this._translation().values);
protected readonly _dir = computed(() => this._translation().dir);
}Brain API
BrnTextarea
Selector: [brnTextarea]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| id | string | undefined | `brn-textarea-${++BrnTextarea._id}` | The id of the textarea. |
| forceInvalid | boolean | false | Whether to force the textarea into an invalid state. |
Helm API
HlmTextarea
Selector: [hlmTextarea]
On This Page
Stop configuring. Start shipping.
Zerops powers spartan.ng and Angular teams worldwide.
One-command deployment. Zero infrastructure headaches.
Deploy with Zerops