Data Table
This is an in-depth guide on how to use the NvDatatable component, covering column configuration, custom cell rendering, pagination modes, and best practices. For API documentation and interactive examples, see the component documentation.
Key Features
- Custom Cell Renderers: Full control over cell content with custom render functions using Angular standalone components
- Full TypeScript Support: Comprehensive type definitions with generic row typing for complete type safety
- Unified Mode Control: Single
modeprop controls client/server behavior for sorting and pagination - Three Pagination Modes: Client-side, server-side, and infinite scroll pagination support
- Extensive Column Configuration: Control width, resizing, hiding, and custom headers with flexible configuration options
- Built on TanStack Table: Leverages the industry-standard TanStack Table library for robust, performant data management
Basic Usage
The simplest implementation requires defining a standalone component with column definitions and row data:
import { Component, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableColumn, makeColumn } from '@nova-design-system/nova-angular';
// Define interface for rows
interface Employee {
id: number;
name: string;
email: string;
department: string;
salary: number;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns" [rows]="rows"></nv-datatable>
`,
})
export class MyComponent {
// Create column factory
col = makeColumn<Employee>();
// Define columns
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({ field: 'name', headerName: 'Full Name' }),
this.col({ field: 'email', headerName: 'Email Address' }),
this.col({ field: 'department', headerName: 'Department' }),
this.col({ field: 'salary', headerName: 'Salary' }),
]);
// Define rows
rows = signal<Employee[]>([
{
id: 1,
name: 'John Smith',
email: 'john.smith@company.com',
department: 'Engineering',
salary: 75000,
},
// ... more data
]);
}
Advanced Column Configuration
Columns support extensive configuration options for precise control. View the full column configuration reference for details.
import { Component, input, output, ChangeDetectionStrategy, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
NovaComponentsModule,
nvDatatableRenderComponent,
type NvDatatableColumn,
makeColumn,
} from '@nova-design-system/nova-angular';
interface Product {
id: number;
name: string;
category: string;
price: number;
isActive: boolean;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns" [rows]="rows">
<ng-template nvDatatableCell="name" let-context>
<div class="font-semibold">{{ context.getValue() }}</div>
</ng-template>
<ng-template nvDatatableCell="price" let-context>
<span class="font-mono text-feedback-success-low">
${{ typeof context.getValue() === 'number' ? context.getValue().toFixed(2) : '0.00' }}
</span>
</ng-template>
<ng-template nvDatatableCell="status" let-context>
<nv-badge
[label]="context.getValue()"
[color]="context.getValue() === 'active' ? 'success' : 'error'"
/>
</ng-template>
</nv-datatable>
`,
})
export class AdvancedComponent {
col = makeColumn(); // Column factory
columns = computed<NvDatatableColumn[]>(() => [
this.col({
field: 'name',
headerName: 'Product Name',
width: 200,
resizable: true,
}),
this.col({
field: 'price',
headerName: 'Price',
width: 120,
// Format number to currency string
valueFormatter: ({ value }) => `$${value.toFixed(2)}`,
}),
this.col({
field: 'status',
headerName: 'Status',
// No width specified - this column will take remaining space
}),
]);
rows = signal<Product[]>([
{
id: 1,
name: 'Laptop Pro',
price: 1299.99,
status: 'active',
},
// ... more data
]);
}
Typescript
The NvDatatable component provides full TypeScript support with automatic type inference using the makeColumn factory function. This ensures type safety throughout your column definitions, especially when using valueFormatter and renderCell.
Using makeColumn Factory
The recommended approach is to use the makeColumn factory function:
import { Component, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableColumn, makeColumn } from '@nova-design-system/nova-angular';
// Define your data interface
interface Employee {
id: number;
name: string;
email: string;
salary: number;
isActive: boolean;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns()" [rows]="employees()"></nv-datatable>
`,
})
export class MyComponent {
// Create a column factory for your data type
col = makeColumn<Employee>();
// Define columns with full type safety
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({ field: 'id', headerName: 'ID' }),
this.col({ field: 'name', headerName: 'Name' }),
this.col({ field: 'email', headerName: 'Email' }),
this.col({ field: 'salary', headerName: 'Salary' }),
]);
// Use with your data
employees = signal<Employee[]>([
{ id: 1, name: 'John Doe', email: 'john@example.com', salary: 75000, isActive: true },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', salary: 85000, isActive: true },
]);
}
Type Flow with valueFormatter
The makeColumn factory ensures that when you use valueFormatter, the return type automatically flows to renderCell:
import { Component, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule, nvDatatableRenderComponent } from '@nova-design-system/nova-angular';
interface Employee {
id: number;
name: string;
salary: number; // number type
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns()" [rows]="employees()">
<!-- Template receives FORMATTED value (string) -->
<ng-template nvDatatableCell="salary" let-context>
<span class="font-mono">{{ context.getValue() }}</span>
<!-- value is typed as string, not number -->
</ng-template>
</nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<Employee>();
columns = computed(() => [
this.col({
field: 'salary',
headerName: 'Salary',
// valueFormatter receives number, returns string
valueFormatter: ({ value }) => `$${value.toLocaleString()}`,
// renderCell receives the formatted string (not the original number)
renderCell: (context) => {
const formattedValue = context.getValue(); // typed as string ✓
return `<span class="font-mono">${formattedValue}</span>`;
}
}),
]);
employees = signal<Employee[]>([
{ id: 1, name: 'John Doe', salary: 75000 },
{ id: 2, name: 'Jane Smith', salary: 85000 },
]);
}
Complex Data Types
The factory function works seamlessly with complex data types like objects and arrays:
import { Component, computed, signal } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableColumn, makeColumn } from '@nova-design-system/nova-angular';
interface User {
id: number;
name: { first: string; last: string };
skills: string[];
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns()" [rows]="users()"></nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<User>();
columns = computed<NvDatatableColumn<User>[]>(() => [
this.col({
field: 'name',
headerName: 'Full Name',
// Transform nested object to string
valueFormatter: ({ value }) => `${value.first} ${value.last}`,
}),
this.col({
field: 'skills',
headerName: 'Skills',
// Transform array to string
valueFormatter: ({ value }) => value.join(', '),
}),
]);
users = signal<User[]>([
{
id: 1,
name: { first: 'John', last: 'Doe' },
skills: ['TypeScript', 'Angular', 'Testing'],
},
{
id: 2,
name: { first: 'Jane', last: 'Smith' },
skills: ['JavaScript', 'React', 'Node.js'],
},
]);
}
Automatic Column Generation
When you don't provide column definitions, NvDatatable inspects the row data and builds the columns for you. This is handy for quickly displaying data without wiring up a column for every field.
<!-- Omit [columns] — the datatable infers them from the row data -->
<nv-datatable [rows]="rows" [sorting]="{}"></nv-datatable>
The generated columns follow these rules:
- One column per key found in the data (the union of keys across the first rows, in first-seen order).
- Headers are humanized from field names —
firstNamebecomes "First Name",created_atbecomes "Created At". - Cells are rendered based on the inferred value type:
- Boolean → centered
True/Falsetext - Number → right-aligned
- Date (a
Datevalue or ISO date string) → locale-formatted - Object / array → compact JSON
- String → rendered as-is
- Boolean → centered
- Sorting and filtering keep operating on the raw underlying values, not the formatted display text.
- Explicit columns always take precedence — provide
[columns]to override any or all of the generated columns.
Tip: You can control cell alignment on any column (generated or explicit) with the
alignproperty:'left' | 'center' | 'right'.
Columns
Each column definition supports the following properties:
| Property | Required | Type | Description |
|---|---|---|---|
field | ✅ | keyof Row | The key from your data object to display |
headerName | - | string | Custom header text (defaults to field name) |
width | - | number | Column width in pixels |
align | - | 'left' | 'center' | 'right' | Horizontal alignment of the column's cell content. Explicit columns default to left; auto-generated columns default to center (numbers right-aligned) |
resizable | - | boolean | Whether users can resize the column (default: true) |
hidden | - | boolean | Hide the column from display |
valueFormatter | - | function | Transform raw value before rendering |
renderCell | - | function | Custom cell rendering function returning FlexRenderComponent |
Value Formatters
The valueFormatter function transforms raw cell values before rendering, providing a clean way to handle common data transformations without requiring full render functions.
When to Use valueFormatter vs renderCell
- Use
valueFormatterwhen you need to transform data to a different format (dates, arrays, nested objects) but don't need custom Angular components or styling - Use
renderCellwhen you need custom presentation with styled components, badges, buttons, or complex layouts - Use both together to first transform the data with
valueFormatter, then style it withrenderCell
Function Signature
valueFormatter?: (params: NvTableValueFormatterParams<Row, Row[K], K>) => F;
Function Parameters:
The function receives a single params object with the following properties:
| Parameter | Type | Description |
|---|---|---|
value | Row[K] | The raw cell value from the data |
row | Row | The complete row object (useful for accessing other fields) |
field | K | The field name being formatted |
Returns: Any type F that will be passed to renderCell or templates. The transformed value automatically flows to cell renderers.
Common Use Cases
Format Dates:
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({
field: 'birthDate',
headerName: 'Birth Date',
valueFormatter: ({ value }) => {
return new Date(value as string).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
},
}),
]);
Join Arrays:
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({
field: 'skills',
headerName: 'Skills',
valueFormatter: ({ value }) => {
const skills = value as string[];
return Array.isArray(skills) ? skills.join(', ') : '';
},
}),
]);
Access Nested Objects:
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({
field: 'person',
headerName: 'Full Name',
valueFormatter: ({ value }) => {
const person = value as { first: string; last: string };
return `${person.first} ${person.last}`;
},
}),
]);
Combining valueFormatter with renderCell
You can use both together - the valueFormatter runs first to transform the data, then renderCell handles the presentation:
// Status Badge Component
@Component({
selector: 'app-status-badge',
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-badge
[label]="status()"
[color]="status() === 'Active' ? 'success' : 'error'">
</nv-badge>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StatusBadgeComponent {
readonly status = input.required<string>();
}
// Usage in column definitions
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Employee>[]>(() => [
{
field: 'isActive',
headerName: 'Status',
// First, format the boolean to a string
valueFormatter: ({ value }) => (value ? 'Active' : 'Inactive'),
// Then, style it with a badge
renderCell: (context) => {
const status = context.getValue() as string;
return nvDatatableRenderComponent(StatusBadgeComponent, {
inputs: { status },
});
},
},
];
Combining valueFormatter with Templates
The formatted value automatically flows to ng-templates:
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule, NvDatatableCellDirective],
template: `
<nv-datatable [columns]="columns" [rows]="employees">
<!-- Template receives FORMATTED value (string) -->
<ng-template nvDatatableCell="skills" let-context>
<div class="text-sm">{{ context.getValue() }}</div>
<!-- value is "JavaScript, React, TypeScript", not an array -->
</ng-template>
</nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({
field: 'skills', // Array type: string[]
valueFormatter: ({ value }) => {
const skills = value as string[];
return skills.join(', '); // Returns string
},
// Template receives the string, not the array
}),
]);
}
Custom Cell Renderers
There are two ways to customize cell rendering: ng-templates (recommended) or standalone components.
Option 1: Template-Based (Recommended)
Use the nvDatatableCell directive for clean, template-based cell customization. Each column can have its own template using the directive with the field name.
Template Parameters:
The template receives TanStack Table's CellContext directly via $implicit. Access cell data using these methods:
| Method/Property | Type | Description |
|---|---|---|
context.getValue() | Row[K] | The cell's actual value (after valueFormatter if provided) |
context.row.original | Row | Complete row object for accessing other fields |
context.row.id | string | The column identifier |
context.row.index | number | Zero-based row index |
Examples:
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule, NvDatatableCellDirective],
template: `
<nv-datatable [columns]="columns" [rows]="products">
<!-- Format currency -->
<ng-template nvDatatableCell="price" let-context>
<span class="font-mono">
{{ context.getValue() | currency:'USD':'symbol':'1.2-2' }}
</span>
</ng-template>
<!-- Status badge -->
<ng-template nvDatatableCell="status" let-context>
<nv-badge
[label]="context.getValue()"
[color]="context.getValue() === 'active' ? 'success' : 'error'"
/>
</ng-template>
<!-- Actions with access to full row -->
<ng-template nvDatatableCell="id" let-context>
<nv-button (click)="editProduct(context.row.original)">Edit</nv-button>
<nv-button (click)="deleteProduct(context.row.original)">Delete</nv-button>
</ng-template>
</nv-datatable>
`,
})
export class MyComponent {
// Simple column definitions - no renderCell needed!
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Product>[]>(() => [
this.col({ field: 'name', headerName: 'Product Name' }),
this.col({ field: 'price', headerName: 'Price' }),
this.col({ field: 'status', headerName: 'Status' }),
this.col({ field: 'id', headerName: 'Actions' }),
]);
products: Product[] = [/* ... */];
editProduct(product: Product) {
console.log('Edit:', product);
}
deleteProduct(product: Product) {
console.log('Delete:', product);
}
}
Option 2: Component-Based
For complex cell logic or highly reusable components, use nvDatatableRenderComponent with standalone components.
Function Parameters: CellContext<Row, Row[K]>
The renderCell function receives a context object with the following properties:
| Method/Property | Type | Description |
|---|---|---|
context.getValue() | Row[K] | The cell's actual value |
context.row.original | Row | Complete row object for accessing other fields |
context.column.id | string | The column identifier |
context.row.index | number | Zero-based row index |
Examples:
@Component({
selector: 'app-currency-cell',
standalone: true,
imports: [CommonModule],
template: `
<span class="font-mono">
{{ value() | currency:'USD':'symbol':'1.2-2' }}
</span>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CurrencyCellComponent {
readonly value = input.required<number>();
}
@Component({
selector: 'app-status-badge',
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-badge
[label]="statusLabel()"
[color]="statusColor()">
</nv-badge>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class StatusBadgeComponent {
readonly status = input.required<string>();
statusLabel = computed(() => {
const labels: Record<string, string> = {
active: 'Active',
inactive: 'Inactive',
pending: 'Pending Review'
};
return labels[this.status()] || this.status();
});
statusColor = computed(() => {
const colors: Record<string, string> = {
active: 'success',
inactive: 'error',
pending: 'warning'
};
return colors[this.status()] || 'neutral';
});
}
col = makeColumn<Employee>();
columns = computed<NvDatatableColumn<Product>[]>(() => [
this.col({
field: 'price',
renderCell: (context) => {
const price = context.getValue();
return nvDatatableRenderComponent(CurrencyCellComponent, {
inputs: { value: price },
});
},
}),
this.col({
field: 'status',
headerName: 'Status',
renderCell: (context) => {
const status = context.getValue();
return nvDatatableRenderComponent(StatusBadgeComponent, {
inputs: { status },
});
},
}),
]);
Priority: If both a template and renderCell are defined for the same column, the template takes precedence.
Column Width Best Practices
When configuring column widths, follow these guidelines for optimal behavior:
⚠️ Important: Do not set width on ALL columns. Always leave at least one column without a specified width to take up the remaining space. Setting widths on every column can cause column resizing to behave incorrectly due to browser table rendering constraints.
Good Practice:
columns: NvDatatableColumn<MyData>[] = [
{ field: 'id', width: 80 }, // Fixed narrow column
{ field: 'name', width: 200 }, // Fixed wider column
{ field: 'email' }, // No width - takes remaining space
{ field: 'actions', width: 150 }, // Fixed action column
];
Avoid:
columns: NvDatatableColumn<MyData>[] = [
{ field: 'id', width: 80 }, // ❌ All columns have width
{ field: 'name', width: 200 }, // ❌ Can cause resizing issues
{ field: 'email', width: 300 }, // ❌ Browser table constraints
{ field: 'actions', width: 150 }, // ❌ No flexible column
];
Tips:
- Set fixed widths for columns with predictable content (IDs, actions, status badges)
- Leave content columns (names, descriptions) without fixed widths for flexibility
- Use horizontal scrolling for tables with many columns rather than cramming them into viewport
- Note: Even with fixed widths, columns may still expand if:
- Users manually resize columns (when resizable is enabled)
- Content is too wide to fit and cannot be wrapped or collapsed (browser will auto-expand to prevent overflow)
Pagination
NvDatatable supports three pagination modes to handle different data loading scenarios:
Pagination Modes
- Client-Side Pagination: All data is loaded at once, pagination handled in the browser
- Server-Side Pagination: Data fetched page-by-page from server with button navigation
- Infinite Scroll: Data loads continuously as user scrolls, accumulating all loaded rows
Client-Side Pagination
Best for datasets under a few thousand rows where all data can be loaded at once.
Enable pagination: pass the pagination prop. Default UI: omit paginationTemplate to use the built-in nv-paginationtable component.
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatablePaginationConfig, makeColumn } from '@nova-design-system/nova-angular';
interface Employee {
id: number;
name: string;
email: string;
department: string;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<!-- Enable pagination + use default nv-paginationtable (no paginationTemplate) -->
<nv-datatable
[columns]="columns"
[rows]="allData"
[pagination]="paginationConfig"
></nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<Employee>();
columns = [
this.col({ field: 'id', headerName: 'ID' }),
this.col({ field: 'name', headerName: 'Name' }),
this.col({ field: 'email', headerName: 'Email' }),
this.col({ field: 'department', headerName: 'Department' }),
];
allData: Employee[] = [
{ id: 1, name: 'John Doe', email: 'john@example.com', department: 'Engineering' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', department: 'Marketing' },
// ... more data (100+ rows)
];
paginationConfig: NvDatatablePaginationConfig = {
mode: 'client',
initialPageSize: 20,
pageSizeOptions: [10, 20, 50, 100],
};
}
Custom pagination UI: use paginationTemplate to render your own controls:
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="allData"
[pagination]="paginationConfig"
>
<ng-template #paginationTemplate let-api>
<div style="display: flex; gap: 8px; margin-top: 16px;">
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canPreviousPage"
(click)="api.previousPage()">
Previous
</nv-button>
<span>Page {{ api.pageIndex + 1 }} of {{ api.pageCount }}</span>
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canNextPage"
(click)="api.nextPage()">
Next
</nv-button>
<select
[value]="api.pageSize"
(change)="api.setPageSize(+$any($event.target).value)">
<option *ngFor="let size of [10, 20, 50]" [value]="size">
{{ size }} rows
</option>
</select>
</div>
</ng-template>
</nv-datatable>
`,
})
export class MyComponent {
columns = [/* ... */];
allData = [/* all 100 rows */];
paginationConfig: NvDatatablePaginationConfig = {
mode: 'client',
initialPageSize: 20,
pageSizeOptions: [10, 20, 50, 100],
};
}
Key Points:
- Pass all data to the
rowsinput - Table handles pagination logic internally
- Default UI: When
paginationTemplateis not provided, the datatable automatically rendersnv-paginationtablecomponent (client mode only) - Use
paginationTemplateto create custom controls - No server requests needed for page changes
Server-Side Pagination
Best for large datasets where you want to fetch data page-by-page.
⚠️ Important: In server-side mode, you must provide your own pagination UI via the paginationTemplate. Unlike client-side mode, the default nv-paginationtable component is not automatically rendered in server mode. This is because server-side pagination requires custom logic to fetch data from your API when users navigate between pages.
import { Component, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatablePaginationConfig } from '@nova-design-system/nova-angular';
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="data()"
[pagination]="paginationConfig()"
>
<ng-template #paginationTemplate let-api>
<div style="display: flex; gap: 8px; margin-top: 16px;">
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canPreviousPage"
(click)="api.firstPage()">
First
</nv-button>
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canPreviousPage"
(click)="api.previousPage()">
Previous
</nv-button>
<span>Page {{ api.pageIndex + 1 }} of {{ api.pageCount }}</span>
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canNextPage"
(click)="api.nextPage()">
Next
</nv-button>
<nv-button
size="sm"
emphasis="low"
[disabled]="!api.canNextPage"
(click)="api.lastPage()">
Last
</nv-button>
</div>
</ng-template>
</nv-datatable>
`,
})
export class MyComponent {
columns = [/* ... */];
currentPage = signal(0);
pageSize = signal(10);
data = signal<MyData[]>([]);
totalCount = signal(0);
paginationConfig = computed<NvDatatablePaginationConfig>(() => ({
mode: 'server',
totalRowCount: this.totalCount(),
initialPageSize: 10,
onPaginationChange: (state) => {
this.currentPage.set(state.pageIndex);
this.pageSize.set(state.pageSize);
this.fetchData();
},
}));
constructor() {
this.fetchData();
}
async fetchData() {
const response = await fetch(
`/api/data?page=${this.currentPage() + 1}&limit=${this.pageSize()}`
);
const json = await response.json();
this.data.set(json.data);
this.totalCount.set(json.total);
}
}
Key Points:
- ⚠️ Required: You must provide
paginationTemplateto display pagination controls (no default UI in server mode) - Pass only current page data to
rowsinput (data is replaced on page change) - Provide
totalRowCountortotalPageCount - Use
onPaginationChangecallback to fetch new data - Parent component manages which page to display
Infinite Scroll
Best for continuously loading data as user scrolls, like social media feeds.
import { Component, signal, computed, untracked } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatablePaginationConfig } from '@nova-design-system/nova-angular';
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<div style="max-height: 600px; overflow: auto;">
<nv-datatable
[stickyHeader]="true"
[columns]="columns"
[rows]="loadedData()"
[pagination]="paginationConfig()"
>
<ng-template #paginationTemplate let-api>
@if (api.isLoading) {
<div style="padding: 16px; text-align: center;">
Loading more...
</div>
} @else if (api.hasMore) {
<div style="padding: 16px; text-align: center;">
Scroll to load more
</div>
} @else {
<div style="padding: 16px; text-align: center;">
All data loaded
</div>
}
</ng-template>
</nv-datatable>
</div>
`,
})
export class MyComponent {
columns = [/* ... */];
loadedData = signal<MyData[]>([]);
isLoading = signal(false);
hasMore = computed(() => this.loadedData().length < this.totalCount());
totalCount = signal(0);
paginationConfig = computed<NvDatatablePaginationConfig>(() => ({
mode: 'infinite',
hasMore: this.hasMore(),
isLoading: this.isLoading(),
loadMoreThreshold: 500, // px from bottom to trigger load
onLoadMore: () => this.loadMore(),
totalRowCount: this.totalCount(),
}));
constructor() {
this.fetchInitialData();
}
async loadMore() {
if (this.isLoading() || !this.hasMore()) return;
this.isLoading.set(true);
const newData = await fetchNextPage();
this.loadedData.set([...this.loadedData(), ...newData]); // Append new data
this.isLoading.set(false);
}
}
Key Points:
- Pass accumulated data to
rowsinput (data is appended on load) - Wrap table in scrollable container or let it grow naturally
- Uses IntersectionObserver to detect when last row is near viewport
- Parent component maintains accumulated data array
- Set
hasMore: falsewhen all data is loaded
Pagination Configuration
| Property | Required | Type | Default | Description |
|---|---|---|---|---|
mode | ✅ | 'client' | 'server' | 'infinite' | - | Pagination mode |
initialPageSize | - | number | 10 | Initial page size |
pageSizeOptions | - | number[] | [10, 25, 50, 100] | Available page size options |
| Server-side specific | ||||
totalRowCount | - | number | - | Total number of rows (for server-side pagination) |
totalPageCount | - | number | - | Total number of pages (for server-side pagination) |
onPaginationChange | - | function | - | Callback when pagination state changes |
| Infinite scroll specific | ||||
hasMore | - | boolean | - | Whether there are more items to load |
isLoading | - | boolean | - | Whether data is currently loading |
loadMoreThreshold | - | number | 500 | Distance from bottom in pixels to trigger load |
onLoadMore | - | function | - | Callback to load more data |
Pagination API
Default Pagination Behavior:
- Client mode: When
paginationTemplateis not provided, the datatable automatically renders thenv-paginationtablecomponent with full pagination controls. - Server mode: When
paginationTemplateis not provided, no pagination UI is displayed. You must providepaginationTemplateto create your own pagination controls.
Custom Pagination:
The paginationTemplate receives an API object with these properties and methods:
| Property | Type | Description |
|---|---|---|
| Current state | ||
pageIndex | number | Current page (zero-based) |
pageSize | number | Rows per page |
pageCount | number | Total number of pages |
rowCount | number | Total number of rows |
| Navigation methods | ||
firstPage | () => void | Navigate to first page |
previousPage | () => void | Navigate to previous page |
nextPage | () => void | Navigate to next page |
lastPage | () => void | Navigate to last page |
setPageIndex | (index: number) => void | Navigate to specific page by index |
setPageSize | (size: number) => void | Change page size |
| State queries | ||
canPreviousPage | boolean | Whether previous page is available |
canNextPage | boolean | Whether next page is available |
| Infinite scroll only | ||
isLoading | boolean | Currently loading data |
hasMore | boolean | More data available |
Sorting
NvDatatable supports both client-side and server-side sorting with extensive customization options. Sorting is enabled by providing a sorting configuration object.
Sorting Modes
- Client-Side Sorting: Data is sorted in the browser using the provided data
- Server-Side Sorting: Sorting is handled by your server, with callbacks for sort changes
Client-Side Sorting
Best for smaller datasets where all data is available in the browser.
import { Component, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableSortingConfig, type NvDatatableColumn, makeColumn } from '@nova-design-system/nova-angular';
interface Employee {
id: number;
name: string;
email: string;
department: string;
salary: number;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="employees()"
[sorting]="sortingConfig">
</nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<Employee>();
// Enable client-side sorting
sortingConfig: NvDatatableSortingConfig = {
mode: 'client',
enableMultiSort: true, // Allow sorting by multiple columns
enableSortingRemoval: true, // Allow clearing sort by clicking again
sortDescFirst: false, // Start with ascending sort
};
// Column definitions with sorting configuration
columns = computed<NvDatatableColumn<Employee>[]>(() => [
this.col({
field: 'name',
headerName: 'Full Name',
sortable: true, // Enable sorting for this column
}),
this.col({
field: 'email',
headerName: 'Email',
sortable: true,
}),
this.col({
field: 'department',
headerName: 'Department',
sortable: true,
}),
this.col({
field: 'salary',
headerName: 'Salary',
sortable: true,
sortDescFirst: true, // Start with descending sort for salary
}),
this.col({
field: 'id',
headerName: 'Actions',
sortable: false, // Disable sorting for actions column
}),
]);
employees = signal<Employee[]>([
{
id: 1,
name: 'John Smith',
email: 'john.smith@company.com',
department: 'Engineering',
salary: 75000,
},
{
id: 2,
name: 'Jane Doe',
email: 'jane.doe@company.com',
department: 'Marketing',
salary: 65000,
},
// ... more employees
]);
}
Initial Sort State (Uncontrolled)
When you want the table to start sorted by a specific column but still let users change the sort by clicking headers, use initialSortState. It seeds the internal sort state on first render only — unlike sortState, it does not make the component controlled.
import { Component, signal } from '@angular/core';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableSortingConfig } from '@nova-design-system/nova-angular';
@Component({
standalone: true,
imports: [NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="products()"
[sorting]="sortingConfig">
</nv-datatable>
`,
})
export class MyComponent {
sortingConfig: NvDatatableSortingConfig = {
mode: 'client',
initialSortState: [{ id: 'price', desc: true }],
};
}
When to use which:
initialSortState: your API returns unsorted data and you want a sensible default sort, but users should still be able to re-sort freely.sortState+onSortingChange: you need full control over sorting (e.g. server-side sorting, URL sync). PassingsortStatemakes the component controlled, so header clicks only take effect if you updatesortStateyourself in the callback.
If both sortState and initialSortState are provided, sortState wins.
Server-Side Sorting
Best for large datasets where sorting should be handled by your backend.
import { Component, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NovaComponentsModule } from '@nova-design-system/nova-angular';
import { type NvDatatableSortingConfig, type NvDataTableSortingState } from '@nova-design-system/nova-angular';
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="data()"
[sorting]="sortingConfig()"
[pagination]="paginationConfig()">
</nv-datatable>
`,
})
export class MyComponent {
currentSort = signal<NvDataTableSortingState>([]);
data = signal<Employee[]>([]);
totalCount = signal(0);
currentPage = signal(0);
pageSize = signal(10);
// Server-side sorting configuration
sortingConfig = computed<NvDatatableSortingConfig>(() => ({
mode: 'server',
enableMultiSort: true,
enableSortingRemoval: true,
sortState: this.currentSort(), // Controlled sort state
onSortingChange: (sorting) => {
this.currentSort.set(sorting);
this.currentPage.set(0); // Reset to first page when sorting changes
this.fetchData();
},
}));
paginationConfig = computed(() => ({
mode: 'server' as const,
totalRowCount: this.totalCount(),
onPaginationChange: (state: { pageIndex: number; pageSize: number }) => {
this.currentPage.set(state.pageIndex);
this.pageSize.set(state.pageSize);
this.fetchData();
},
}));
constructor() {
this.fetchData();
}
async fetchData() {
const sortParams = this.currentSort().map(sort =>
`${sort.id}:${sort.desc ? 'desc' : 'asc'}`
).join(',');
const params = new URLSearchParams({
page: (this.currentPage() + 1).toString(),
limit: this.pageSize().toString(),
sort: sortParams,
});
const response = await fetch(`/api/employees?${params}`);
const json = await response.json();
this.data.set(json.data);
this.totalCount.set(json.total);
}
columns = computed(() => [
this.col({ field: 'name', headerName: 'Name', sortable: true }),
this.col({ field: 'email', headerName: 'Email', sortable: true }),
this.col({ field: 'salary', headerName: 'Salary', sortable: true }),
this.col({ field: 'department', headerName: 'Department', sortable: true }),
]);
}
Multi-Column Sorting
Enable users to sort by multiple columns simultaneously:
sortingConfig: NvDatatableSortingConfig = {
mode: 'client',
enableMultiSort: true, // Enable multi-column sorting
maxMultiSortColCount: 3, // Limit to 3 columns max
enableSortingRemoval: true, // Allow clearing sorts
};
Usage:
- Single sort: Click column header to sort by that column
- Multi-sort: With
enableMultiSort: true, all column header clicks add to the sort criteria - Clear sort: Click a sorted column again to remove it from sort criteria (when
enableSortingRemoval: true)
Custom Sorting Functions
Provide custom sorting logic for specific columns:
import { Component, computed } from '@angular/core';
interface Product {
name: string;
category: string;
rating: number;
tags: string[];
createdAt: string;
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable
[columns]="columns"
[rows]="products"
[sorting]="sortingConfig">
</nv-datatable>
`,
})
export class MyComponent {
col = makeColumn<Product>();
sortingConfig: NvDatatableSortingConfig = {
mode: 'client',
enableMultiSort: false,
};
columns = computed<NvDatatableColumn<Product>[]>(() => [
this.col({
field: 'name',
headerName: 'Product Name',
sortable: true,
// Case-insensitive string sorting
sortingFn: (rowA, rowB, columnId) => {
const a = rowA.original.name.toLowerCase();
const b = rowB.original.name.toLowerCase();
return a.localeCompare(b);
},
}),
this.col({
field: 'tags',
headerName: 'Tags',
valueFormatter: ({ value }) => value.join(', '),
sortable: true,
// Sort by number of tags, then alphabetically by first tag
sortingFn: (rowA, rowB, columnId) => {
const tagsA = rowA.original.tags;
const tagsB = rowB.original.tags;
// First, sort by number of tags
const lengthDiff = tagsA.length - tagsB.length;
if (lengthDiff !== 0) return lengthDiff;
// Then sort by first tag alphabetically
const firstTagA = tagsA[0] || '';
const firstTagB = tagsB[0] || '';
return firstTagA.localeCompare(firstTagB);
},
}),
this.col({
field: 'createdAt',
headerName: 'Created',
valueFormatter: ({ value }) => new Date(value).toLocaleDateString(),
sortable: true,
// Date sorting
sortingFn: (rowA, rowB, columnId) => {
const dateA = new Date(rowA.original.createdAt);
const dateB = new Date(rowB.original.createdAt);
return dateA.getTime() - dateB.getTime();
},
}),
this.col({
field: 'rating',
headerName: 'Rating',
sortable: true,
sortDescFirst: true, // Start with highest ratings first
// Handle undefined values in sorting
sortUndefined: 'last', // Put undefined ratings at the end
}),
]);
products: Product[] = [
{
name: 'TypeScript Handbook',
category: 'Books',
rating: 4.8,
tags: ['programming', 'typescript', 'reference'],
createdAt: '2023-01-15T10:00:00Z',
},
// ... more products
];
}
Column-Specific Sorting Options
Each column supports individual sorting configuration:
columns = computed<NvDatatableColumn<MyData>[]>(() => [
this.col({
field: 'name',
sortable: true, // Enable sorting
sortDescFirst: false, // Start with ascending (A-Z)
}),
this.col({
field: 'priority',
sortable: true,
sortDescFirst: true, // Start with descending (High to Low)
invertSorting: false, // Normal sort order
sortUndefined: 'last', // Put undefined values last
}),
this.col({
field: 'rank',
sortable: true,
invertSorting: true, // Invert sort order (useful for rankings)
sortDescFirst: false, // Start ascending, but inverted means high numbers first
}),
this.col({
field: 'actions',
sortable: false, // Disable sorting for this column
}),
]);
Sorting Configuration Options
| Property | Type | Default | Description |
|---|---|---|---|
mode | 'client' | 'server' | - | Required. How sorting is handled |
enableMultiSort | boolean | false | Allow sorting by multiple columns |
enableSortingRemoval | boolean | true | Allow clearing sort by clicking sorted column |
maxMultiSortColCount | number | undefined | Maximum columns for multi-sort |
sortDescFirst | boolean | false | Global default for starting with descending sort |
initialSortState | SortingState | [] | Uncontrolled initial sort applied on first render; ignored when sortState is set |
sortState | SortingState | [] | Controlled sort state (server mode) |
onSortingChange | function | - | Callback when sort state changes (server mode) |
Column Sorting Options
| Property | Type | Default | Description |
|---|---|---|---|
sortable | boolean | true | Enable/disable sorting for this column |
sortingFn | function | string | 'auto' | Custom sorting function or built-in function name |
sortDescFirst | boolean | false | Start with descending sort for this column |
invertSorting | boolean | false | Invert the sort order (useful for rankings) |
sortUndefined | 'first' | 'last' | false | false | Where to place undefined values |
Built-in Sorting Functions
TanStack Table provides several built-in sorting functions you can reference by name:
columns = computed(() => [
this.col({
field: 'name',
sortingFn: 'text', // Text sorting (case-insensitive)
}),
this.col({
field: 'count',
sortingFn: 'basic', // Basic comparison (numbers, strings)
}),
this.col({
field: 'date',
sortingFn: 'datetime', // Date/time sorting
}),
this.col({
field: 'amount',
sortingFn: 'alphanumeric', // Natural alphanumeric sorting
}),
]);
Sorting State Management
For advanced use cases, you can access and control the sorting state:
import { Component, signal, computed, effect } from '@angular/core';
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<div>
<!-- Sort controls -->
<div style="margin-bottom: 16px;">
<nv-button (click)="sortByName()">Sort by Name</nv-button>
<nv-button (click)="sortBySalary()">Sort by Salary (Desc)</nv-button>
<nv-button (click)="clearSort()">Clear Sort</nv-button>
</div>
<!-- Current sort display -->
<div style="margin-bottom: 16px;">
<strong>Current Sort:</strong>
@if (currentSort().length === 0) {
<span>No sorting applied</span>
} @else {
@for (sort of currentSort(); track sort.id) {
<span>{{ sort.id }} ({{ sort.desc ? 'desc' : 'asc' }})</span>
}
}
</div>
<nv-datatable
[columns]="columns"
[rows]="employees"
[sorting]="sortingConfig()">
</nv-datatable>
</div>
`,
})
export class MyComponent {
currentSort = signal<NvDataTableSortingState>([]);
sortingConfig = computed<NvDatatableSortingConfig>(() => ({
mode: 'client',
enableMultiSort: true,
sortState: this.currentSort(),
onSortingChange: (sorting) => {
this.currentSort.set(sorting);
},
}));
// Programmatic sorting methods
sortByName() {
this.currentSort.set([{ id: 'name', desc: false }]);
}
sortBySalary() {
this.currentSort.set([{ id: 'salary', desc: true }]);
}
clearSort() {
this.currentSort.set([]);
}
// Save sort state to localStorage
constructor() {
effect(() => {
localStorage.setItem('tableSortState', JSON.stringify(this.currentSort()));
});
// Load saved sort state
const savedSort = localStorage.getItem('tableSortState');
if (savedSort) {
this.currentSort.set(JSON.parse(savedSort));
}
}
}
Horizontal Scrolling
For tables with many columns or wide content, enable horizontal scrolling by adding CSS classes:
<nv-datatable
[columns]="columns"
[rows]="data"
class="block overflow-x-auto">
</nv-datatable>
Sticky Header
Enable sticky headers to keep column headers visible when scrolling through long tables:
<nv-datatable
[columns]="columns"
[rows]="data"
[stickyHeader]="true">
</nv-datatable>
Angular-Specific Patterns
Reactive Data with Signals
The NvDatatable component works seamlessly with Angular signals:
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<div>
<nv-button (click)="addRow()">Add Row</nv-button>
<nv-button (click)="clearData()">Clear All</nv-button>
<nv-datatable [columns]="columns" [rows]="filteredData()"></nv-datatable>
</div>
`,
})
export class MyComponent {
// Reactive data using signals
private readonly _data = signal<MyData[]>(initialData);
private readonly _filter = signal<string>('');
// Computed filtered data
filteredData = computed(() => {
const filter = this._filter();
return filter
? this._data().filter(item => item.name.includes(filter))
: this._data();
});
addRow(): void {
this._data.update(data => [...data, newRow]);
}
clearData(): void {
this._data.set([]);
}
setFilter(filter: string): void {
this._filter.set(filter);
}
}
Service Integration
Integrate with Angular services for data management:
@Injectable({
providedIn: 'root'
})
export class DataService {
private readonly http = inject(HttpClient);
getEmployees(): Observable<Employee[]> {
return this.http.get<Employee[]>('/api/employees');
}
deleteEmployee(id: number): Observable<void> {
return this.http.delete<void>(`/api/employees/${id}`);
}
}
@Component({
standalone: true,
imports: [CommonModule, NovaComponentsModule],
template: `
<nv-datatable [columns]="columns" [rows]="employees"></nv-datatable>
`,
})
export class MyComponent implements OnInit {
private readonly dataService = inject(DataService);
employees: Employee[] = [];
ngOnInit(): void {
this.dataService.getEmployees().subscribe(employees => {
this.employees = employees;
});
}
handleDelete(employee: Employee): void {
this.dataService.deleteEmployee(employee.id).subscribe(() => {
this.employees = this.employees.filter(e => e.id !== employee.id);
});
}
}