- 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
- Drawer
- Dropdown Menu
- Empty
- Field
- Hover Card
- 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
Data Table
Powerful table and datagrids similar powered by TanStack Table
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { lucideChevronDown } from '@ng-icons/lucide';
import { HlmButtonImports } from '@spartan-ng/helm/button';
import { HlmDropdownMenuImports } from '@spartan-ng/helm/dropdown-menu';
import { HlmInputImports } from '@spartan-ng/helm/input';
import { HlmTableImports } from '@spartan-ng/helm/table';
import { hlmMuted } from '@spartan-ng/helm/typography';
import {
type ColumnDef,
type ColumnFiltersState,
createAngularTable,
flexRenderComponent,
FlexRenderDirective,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
type RowSelectionState,
type SortingState,
type VisibilityState,
} from '@tanstack/angular-table';
import { ActionDropdown } from './action-dropdown';
import { TableHeadSelection, TableRowSelection } from './selection-column';
import { TableHeadSortButton } from './sort-header-button';
export type Payment = {
id: string;
amount: number;
status: 'pending' | 'processing' | 'success' | 'failed';
email: string;
};
@Component({
selector: 'spartan-data-table-preview',
imports: [
FlexRenderDirective,
FormsModule,
HlmDropdownMenuImports,
HlmButtonImports,
NgIcon,
HlmInputImports,
HlmTableImports,
],
providers: [provideIcons({ lucideChevronDown })],
host: {
class: 'w-full',
},
template: `
<div class="flex flex-col justify-between gap-4 py-4 sm:flex-row sm:items-center">
<input hlmInput class="w-full md:w-80" placeholder="Filter emails..." (input)="_filterChanged($event)" />
<button hlmBtn variant="outline" align="end" [hlmDropdownMenuTrigger]="menu">
Columns
<ng-icon name="lucideChevronDown" class="ml-2" />
</button>
<ng-template #menu>
<hlm-dropdown-menu class="w-32">
@for (column of _hidableColumns; track column.id) {
<button
hlmDropdownMenuCheckbox
class="capitalize"
[checked]="column.getIsVisible()"
(triggered)="column.toggleVisibility()"
>
<hlm-dropdown-menu-checkbox-indicator />
{{ column.columnDef.id }}
</button>
}
</hlm-dropdown-menu>
</ng-template>
</div>
<div class="overflow-hidden rounded-md border">
<!-- we defer the loading of the table, because tanstack manipulates the DOM with flexRender which can cause errors during SSR -->
@defer {
<div hlmTableContainer>
<table hlmTable>
<thead hlmTHead>
@for (headerGroup of _table.getHeaderGroups(); track headerGroup.id) {
<tr hlmTr>
@for (header of headerGroup.headers; track header.id) {
<th hlmTh [attr.colSpan]="header.colSpan">
@if (!header.isPlaceholder) {
<ng-container
*flexRender="header.column.columnDef.header; props: header.getContext(); let headerText"
>
<div [innerHTML]="headerText"></div>
</ng-container>
}
</th>
}
</tr>
}
</thead>
<tbody hlmTBody>
@for (row of _table.getRowModel().rows; track row.id) {
<tr hlmTr [attr.key]="row.id" [attr.data-state]="row.getIsSelected() && 'selected'">
@for (cell of row.getVisibleCells(); track $index) {
<td hlmTd>
<ng-container *flexRender="cell.column.columnDef.cell; props: cell.getContext(); let cell">
<div [innerHTML]="cell"></div>
</ng-container>
</td>
}
</tr>
} @empty {
<tr hlmTr>
<td hlmTd class="h-24 text-center" [attr.colspan]="_columns.length">No results.</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
<div class="flex flex-col justify-between py-4 sm:flex-row sm:items-center">
@if (_table.getRowCount() > 0) {
<div class="${hlmMuted}">
{{ _table.getSelectedRowModel().rows.length }} of {{ _table.getRowCount() }} row(s) selected
</div>
<div class="mt-2 flex space-x-2 sm:mt-0">
<button
size="sm"
variant="outline"
hlmBtn
[disabled]="!_table.getCanPreviousPage()"
(click)="_table.previousPage()"
>
Previous
</button>
<button size="sm" variant="outline" hlmBtn [disabled]="!_table.getCanNextPage()" (click)="_table.nextPage()">
Next
</button>
</div>
} @else {
<div class="flex h-full w-full items-center justify-center">
<div class="text-muted-foreground text-sm">No Data</div>
</div>
}
</div>
`,
})
export class DataTablePreview {
protected _filterChanged(event: Event) {
this._table.getColumn('email')?.setFilterValue((event.target as HTMLInputElement).value);
}
protected readonly _columns: ColumnDef<Payment>[] = [
{
id: 'select',
header: () => flexRenderComponent(TableHeadSelection, { inputs: {} }),
cell: () => flexRenderComponent(TableRowSelection, { inputs: {} }),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: 'status',
id: 'status',
header: 'Status',
enableSorting: false,
cell: (info) => `<span class="capitalize">${info.getValue<string>()}</span>`,
},
{
accessorKey: 'email',
id: 'email',
header: () => flexRenderComponent(TableHeadSortButton, { inputs: { header: '' } }),
cell: (info) => `<div class="lowercase">${info.getValue<string>()}</div>`,
},
{
accessorKey: 'amount',
id: 'amount',
header: '<div class="text-right">Amount</div>',
enableSorting: false,
cell: (info) => {
const amount = parseFloat(info.getValue<string>());
const formatted = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
}).format(amount);
return `<div class="text-right">${formatted}</div>`;
},
},
{
id: 'actions',
enableHiding: false,
cell: () => flexRenderComponent(ActionDropdown, { inputs: {} }),
},
];
private readonly _columnFilters = signal<ColumnFiltersState>([]);
private readonly _sorting = signal<SortingState>([]);
private readonly _rowSelection = signal<RowSelectionState>({});
private readonly _columnVisibility = signal<VisibilityState>({});
protected readonly _table = createAngularTable<Payment>(() => ({
data: PAYMENT_DATA,
columns: this._columns,
onSortingChange: (updater) => {
updater instanceof Function ? this._sorting.update(updater) : this._sorting.set(updater);
},
onColumnFiltersChange: (updater) => {
updater instanceof Function ? this._columnFilters.update(updater) : this._columnFilters.set(updater);
},
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onColumnVisibilityChange: (updater) => {
updater instanceof Function ? this._columnVisibility.update(updater) : this._columnVisibility.set(updater);
},
onRowSelectionChange: (updater) => {
updater instanceof Function ? this._rowSelection.update(updater) : this._rowSelection.set(updater);
},
state: {
sorting: this._sorting(),
columnFilters: this._columnFilters(),
columnVisibility: this._columnVisibility(),
rowSelection: this._rowSelection(),
},
}));
protected readonly _hidableColumns = this._table.getAllColumns().filter((column) => column.getCanHide());
protected _filterChange(email: Event) {
const target = email.target as HTMLInputElement;
const typedValue = target.value;
this._table.setGlobalFilter(typedValue);
}
}
const PAYMENT_DATA: Payment[] = [
{
id: 'm5gr84i9',
amount: 316,
status: 'success',
email: 'ken99@yahoo.com',
},
{
id: '3u1reuv4',
amount: 242,
status: 'success',
email: 'Abe45@gmail.com',
},
{
id: 'derv1ws0',
amount: 837,
status: 'processing',
email: 'Monserrat44@gmail.com',
},
{
id: '5kma53ae',
amount: 874,
status: 'success',
email: 'Silas22@gmail.com',
},
{
id: 'bhqecj4p',
amount: 721,
status: 'failed',
email: 'carmella@hotmail.com',
},
];About
Data-Table is built on top of TanStack-Table by @tannerlinsley and the Table directives.
Installation
Add the Table directives to your project.
ng g @spartan-ng/cli:ui tablenx g @spartan-ng/cli:ui table Add @tanstack/angular-table to your project, more information in the TanStack Table documentation.
npm install @tanstack/angular-tableExamples
For more information you can check out our Tasks example and have a look at the documentation of TanStack Table . TanStack Table provides multiple examples on GitHub and interactive examples on the documentation site. These examples are unstyled and can be used as a foundation for your own implementations using the Table directives to apply consistent styling. Here are some examples to get you started:
- Basic - A basic table example with multiple columns
- Column Visibility - An example of how to implement column visibility
- Column Filters - An example of how to implement column filters
- Row Selection - An example of how to implement row selection
RTL
To enable RTL support in spartan-ng, see the RTL configuration guide.
| العميل | الحالة | المبلغ |
|---|---|---|
| ken99@example.com | ناجح | $316.00 |
| abe45@example.com | قيد المعالجة | $242.00 |
| monserrat44@example.com | فشل | $837.00 |
| carmella@example.com | ناجح | $721.00 |
| المجموع | $1,250.00 | |
import { ChangeDetectionStrategy, Component, computed, inject } from '@angular/core';
import { TranslateService, Translations } from '@spartan-ng/app/app/shared/translate.service';
import { HlmTableImports } from '@spartan-ng/helm/table';
type Payment = {
email: string;
status: 'success' | 'processing' | 'failed';
amount: string;
};
@Component({
selector: 'spartan-data-table-rtl',
imports: [HlmTableImports],
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
class: 'w-full',
},
template: `
<div hlmTableContainer>
<table hlmTable [dir]="_dir()">
<caption hlmTableCaption>{{ _t()['caption'] }}</caption>
<thead hlmTableHeader>
<tr hlmTableRow>
<th hlmTableHead>{{ _t()['customer'] }}</th>
<th hlmTableHead>{{ _t()['status'] }}</th>
<th hlmTableHead class="text-end">{{ _t()['amount'] }}</th>
</tr>
</thead>
<tbody hlmTableBody>
@for (payment of _payments; track payment.email) {
<tr hlmTableRow>
<td hlmTableCell class="font-medium">{{ payment.email }}</td>
<td hlmTableCell>{{ _t()[payment.status] }}</td>
<td hlmTableCell class="text-end">{{ payment.amount }}</td>
</tr>
}
</tbody>
<tfoot hlmTableFooter>
<tr hlmTableRow>
<td hlmTableCell [attr.colSpan]="2">{{ _t()['total'] }}</td>
<td hlmTableCell class="text-end">$1,250.00</td>
</tr>
</tfoot>
</table>
</div>
`,
})
export class DataTableRtl {
protected readonly _payments: Payment[] = [
{ email: 'ken99@example.com', status: 'success', amount: '$316.00' },
{ email: 'abe45@example.com', status: 'processing', amount: '$242.00' },
{ email: 'monserrat44@example.com', status: 'failed', amount: '$837.00' },
{ email: 'carmella@example.com', status: 'success', amount: '$721.00' },
];
private readonly _language = inject(TranslateService).language;
private readonly _translations: Translations = {
en: {
dir: 'ltr',
values: {
caption: 'A list of your recent payments.',
customer: 'Customer',
status: 'Status',
amount: 'Amount',
success: 'Success',
processing: 'Processing',
failed: 'Failed',
total: 'Total',
},
},
ar: {
dir: 'rtl',
values: {
caption: 'قائمة بمدفوعاتك الأخيرة.',
customer: 'العميل',
status: 'الحالة',
amount: 'المبلغ',
success: 'ناجح',
processing: 'قيد المعالجة',
failed: 'فشل',
total: 'المجموع',
},
},
he: {
dir: 'rtl',
values: {
caption: 'רשימת התשלומים האחרונים שלך.',
customer: 'לקוח',
status: 'סטטוס',
amount: 'סכום',
success: 'הצליח',
processing: 'בעיבוד',
failed: 'נכשל',
total: 'סה"כ',
},
},
};
private readonly _translation = computed(() => this._translations[this._language()]);
protected readonly _t = computed(() => this._translation().values);
protected readonly _dir = computed(() => this._translation().dir);
}On This Page