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
- 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
Forms
Stack
Table
Apply responsive styles to a native HTML table.
| Invoice | Status | Method | Amount |
|---|---|---|---|
| INV001 | Paid | Credit Card | $250.00 |
| INV002 | Pending | PayPal | $150.00 |
| INV003 | Unpaid | Bank Transfer | $350.00 |
| INV004 | Paid | Credit Card | $450.00 |
| INV005 | Paid | PayPal | $550.00 |
| INV006 | Pending | Bank Transfer | $200.00 |
| INV007 | Unpaid | Credit Card | $300.00 |
| Total | $2,500.00 | ||
import { Component } from '@angular/core';
import { HlmTableImports } from '@spartan-ng/helm/table';
@Component({
selector: 'spartan-table-preview',
imports: [HlmTableImports],
host: {
class: 'w-full',
},
template: `
<div hlmTableContainer>
<table hlmTable>
<caption hlmCaption>A list of your recent invoices.</caption>
<thead hlmTHead>
<tr hlmTr>
<th hlmTh class="w-[100px]">Invoice</th>
<th hlmTh>Status</th>
<th hlmTh>Method</th>
<th hlmTh class="text-right">Amount</th>
</tr>
</thead>
<tbody hlmTBody>
@for (invoice of _invoices; track invoice.invoice) {
<tr hlmTr>
<td hlmTd class="font-medium">{{ invoice.invoice }}</td>
<td hlmTd>{{ invoice.paymentStatus }}</td>
<td hlmTd>{{ invoice.paymentMethod }}</td>
<td hlmTd class="text-right">{{ invoice.totalAmount }}</td>
</tr>
}
</tbody>
<tfoot hlmTFoot>
<tr hlmTr>
<td hlmTd [attr.colSpan]="3">Total</td>
<td hlmTd class="text-right">$2,500.00</td>
</tr>
</tfoot>
</table>
</div>
`,
})
export class TablePreview {
protected _invoices = [
{
invoice: 'INV001',
paymentStatus: 'Paid',
totalAmount: '$250.00',
paymentMethod: 'Credit Card',
},
{
invoice: 'INV002',
paymentStatus: 'Pending',
totalAmount: '$150.00',
paymentMethod: 'PayPal',
},
{
invoice: 'INV003',
paymentStatus: 'Unpaid',
totalAmount: '$350.00',
paymentMethod: 'Bank Transfer',
},
{
invoice: 'INV004',
paymentStatus: 'Paid',
totalAmount: '$450.00',
paymentMethod: 'Credit Card',
},
{
invoice: 'INV005',
paymentStatus: 'Paid',
totalAmount: '$550.00',
paymentMethod: 'PayPal',
},
{
invoice: 'INV006',
paymentStatus: 'Pending',
totalAmount: '$200.00',
paymentMethod: 'Bank Transfer',
},
{
invoice: 'INV007',
paymentStatus: 'Unpaid',
totalAmount: '$300.00',
paymentMethod: 'Credit Card',
},
];
}Installation
ng g @spartan-ng/cli:ui tablenx g @spartan-ng/cli:ui tableimport { 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 { Directive, InjectionToken, computed, inject, input, type ValueProvider } from '@angular/core';
import { classes } from '@spartan-ng/helm/utils';
// Configuration Interface and InjectionToken
export const HlmTableConfigToken = new InjectionToken<HlmTableVariant>('HlmTableConfig');
export interface HlmTableVariant {
tableContainer: string;
table: string;
thead: string;
tbody: string;
tfoot: string;
tr: string;
th: string;
td: string;
caption: string;
}
export const HlmTableVariantDefault: HlmTableVariant = {
tableContainer: 'relative w-full overflow-x-auto',
table: 'w-full caption-bottom text-sm',
thead: '[&_tr]:border-b',
tbody: '[&_tr:last-child]:border-0',
tfoot: 'bg-muted/50 border-t font-medium [&>tr]:last:border-b-0',
tr: 'hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors',
th: 'text-foreground h-10 px-2 text-start align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pe-0',
td: 'p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pe-0',
caption: 'text-muted-foreground mt-4 text-sm',
};
export function provideHlmTableConfig(config: Partial<HlmTableVariant>): ValueProvider {
return {
provide: HlmTableConfigToken,
useValue: { ...HlmTableVariantDefault, ...config },
};
}
export function injectHlmTableConfig(): HlmTableVariant {
return inject(HlmTableConfigToken, { optional: true }) ?? HlmTableVariantDefault;
}
@Directive({
selector: 'div[hlmTableContainer]',
host: { 'data-slot': 'table-container' },
})
export class HlmTableContainer {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.tableContainer.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <table> element.
* It resolves and provides base classes for its child table elements.
* If a table has the `hlmTable` attribute, it will be styled with the provided variant.
* The other table elements will check if a parent table has the `hlmTable` attribute and will be styled accordingly.
*/
@Directive({
selector: 'table[hlmTable]',
host: { 'data-slot': 'table' },
})
export class HlmTable {
/** Input to configure the variant of the table, this input has the highest priority. */
public readonly userVariant = input<Partial<HlmTableVariant> | string>({}, { alias: 'hlmTable' });
/** Global or default configuration provided by injectHlmTableConfig() */
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
// Protected variant that resolves user input to a full HlmTableVariant
protected readonly _variant = computed<HlmTableVariant>(() => {
const globalOrDefaultConfig = this._globalOrDefaultConfig;
const localInputConfig = this.userVariant();
// Priority 1: Local input object
if (typeof localInputConfig === 'object' && localInputConfig !== null && Object.keys(localInputConfig).length > 0) {
// Merge local input with the baseline provided by injectHlmTableConfig()
// This ensures that properties not in localInputConfig still fall back to global/default values.
return { ...globalOrDefaultConfig, ...localInputConfig };
}
// If localInputConfig is not a non-empty object (e.g., it's undefined, an empty object, or a string),
// then the globalOrDefaultConfig (which is already the result of injected OR default) is used.
return globalOrDefaultConfig;
});
constructor() {
classes(() => this._variant().table);
}
}
// Computed class for the host <table> element}
/**
* Directive to apply Shadcn-like styling to a <thead> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'thead[hlmTHead]',
host: { 'data-slot': 'table-header' },
})
export class HlmTHead {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.thead.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <tbody> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'tbody[hlmTBody]',
host: { 'data-slot': 'table-body' },
})
export class HlmTBody {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.tbody.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <tfoot> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'tfoot[hlmTFoot]',
host: { 'data-slot': 'table-footer' },
})
export class HlmTFoot {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.tfoot.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <tr> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'tr[hlmTr]',
host: { 'data-slot': 'table-row' },
})
export class HlmTr {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.tr.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <th> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'th[hlmTh]',
host: { 'data-slot': 'table-head' },
})
export class HlmTh {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.th.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <td> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'td[hlmTd]',
host: { 'data-slot': 'table-cell' },
})
export class HlmTd {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.td.trim() : ''));
}
}
/**
* Directive to apply Shadcn-like styling to a <caption> element
* within an HlmTableDirective context.
*/
@Directive({
selector: 'caption[hlmCaption]',
host: { 'data-slot': 'table-caption' },
})
export class HlmCaption {
private readonly _globalOrDefaultConfig = injectHlmTableConfig();
constructor() {
classes(() => (this._globalOrDefaultConfig ? this._globalOrDefaultConfig.caption.trim() : ''));
}
}
export const HlmTableImports = [
HlmCaption,
HlmTableContainer,
HlmTable,
HlmTBody,
HlmTd,
HlmTFoot,
HlmTh,
HlmTHead,
HlmTr,
] as const;Usage
import { HlmTableImports } from '@spartan-ng/helm/table';<div hlmTableContainer>
<table hlmTable>
<caption hlmCaption>
A list of your recent invoices.
</caption>
<thead hlmTHead>
<tr hlmTr>
<th hlmTh class="w-[100px]">Invoice</th>
<th hlmTh>Status</th>
<th hlmTh>Method</th>
<th hlmTh class="text-right">Amount</th>
</tr>
</thead>
<tbody hlmTBody>
@for (invoice of _invoices; track invoice.invoice) {
<tr hlmTr>
<td hlmTd class="font-medium">{{ invoice.invoice }}</td>
<td hlmTd>{{ invoice.paymentStatus }}</td>
<td hlmTd>{{ invoice.paymentMethod }}</td>
<td hlmTd class="text-right">{{ invoice.totalAmount }}</td>
</tr>
}
</tbody>
<tfoot hlmTFoot>
<tr hlmTr>
<td hlmTd [attr.colSpan]="3">Total</td>
<td hlmTd class="text-right">$2,500.00</td>
</tr>
</tfoot>
</table>
</div>Data Table
For more complex tables, have a look at the data table , which is powered by the incredible work of TanStack-Table .
See the Data Table documentation for more information.
You can also see an example of a data table in the Tasks demo.
Helm API
HlmTableContainer
Selector: div[hlmTableContainer]
HlmTable
Selector: table[hlmTable]
Inputs
| Prop | Type | Default | Description |
|---|---|---|---|
| hlmTable | Partial<HlmTableVariant> | string | {} | Input to configure the variant of the table, this input has the highest priority. |
HlmTHead
Selector: thead[hlmTHead]
HlmTBody
Selector: tbody[hlmTBody]
HlmTFoot
Selector: tfoot[hlmTFoot]
HlmTr
Selector: tr[hlmTr]
HlmTh
Selector: th[hlmTh]
HlmTd
Selector: td[hlmTd]
HlmCaption
Selector: caption[hlmCaption]
On This Page
Stop configuring. Start shipping.
Zerops powers spartan.ng and Angular teams worldwide.
One-command deployment. Zero infrastructure headaches.
Deploy with Zerops