DataGridElement
High-performance data grid web component (<tbw-grid>).
Instantiation
Section titled “Instantiation”Do not call the constructor directly. Use one of these approaches:
// Recommended: Use createGrid() for TypeScript type safetyimport { createGrid, SelectionPlugin } from '@toolbox-web/grid/all';
const grid = createGrid<Employee>({ columns: [ { field: 'name', header: 'Name' }, { field: 'email', header: 'Email' } ], plugins: [new SelectionPlugin()]});grid.rows = employees;document.body.appendChild(grid);
// Alternative: Query existing element from DOMimport { queryGrid } from '@toolbox-web/grid';const grid = queryGrid<Employee>('#my-grid');
// Alternative: Use document.createElement (loses type inference)const grid = document.createElement('tbw-grid');Events
Section titled “Events”| Event | Description | Triggered By |
|---|---|---|
sort-change | Column header clicked to change sort order | (internal) |
column-resize | Column resized by dragging | (internal) |
activate-cell | Cell activated (Enter key pressed) | (internal) |
mount-external-view | External view renderer needed (framework adapters) | (internal) |
mount-external-editor | External editor renderer needed (framework adapters) | (internal) |
cell-change | For each field that changed on each row | updateRow(), updateRows() |
column-state-change | Emitted when column visibility changes | setColumnVisible(), toggleColumnVisibility(), showAllColumns(), setColumnOrder(), resetColumnState() |
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
tagName | tbw-grid | |
version | string | Version of the grid component, injected at build time from package.json |
Configuration
Section titled “Configuration”Get or set the row data displayed in the grid.
The getter returns processed rows (after filtering, sorting, grouping by plugins). The setter accepts new source data and triggers a re-render.
rows: T[]Example
Section titled “Example”// Set initial datagrid.rows = employees;
// Update with new data (triggers re-render)grid.rows = [...employees, newEmployee];
// Read current (processed) rowsconsole.log(`Displaying ${grid.rows.length} rows`);sourceRows
Section titled “sourceRows”Get the original unfiltered/unprocessed source rows.
Use this when you need access to all source data regardless of active
filters, sorting, or grouping applied by plugins. The rows property
returns processed data, while sourceRows returns the original input.
sourceRows: T[]Example
Section titled “Example”// Get total count including filtered-out rowsconsole.log(`${grid.rows.length} of ${grid.sourceRows.length} rows visible`);
// Export all data, not just visibleexportToCSV(grid.sourceRows);columns
Section titled “columns”Get or set the column configurations.
The getter returns processed columns (after plugin transformations). The setter accepts an array of column configs or a column config map.
columns: ColumnConfig<T>[]Example
Section titled “Example”// Set columns as arraygrid.columns = [ { field: 'name', header: 'Name', width: 200 }, { field: 'email', header: 'Email' }, { field: 'role', header: 'Role', width: 120 }];
// Set columns as map (keyed by field)grid.columns = { name: { header: 'Name', width: 200 }, email: { header: 'Email' }, role: { header: 'Role', width: 120 }};
// Read current columnsgrid.columns.forEach(col => { console.log(`${col.field}: ${col.width ?? 'auto'}`);});gridConfig
Section titled “gridConfig”Get or set the full grid configuration object.
The getter returns the effective (merged) configuration. The setter accepts a new configuration and triggers a full re-render.
gridConfig: GridConfig<T>Example
Section titled “Example”import { SelectionPlugin, SortingPlugin } from '@toolbox-web/grid/all';
// Set full configurationgrid.gridConfig = { columns: [ { field: 'name', header: 'Name' }, { field: 'status', header: 'Status' } ], fitMode: 'stretch', plugins: [ new SelectionPlugin({ mode: 'row' }), new SortingPlugin() ]};
// Read current configurationconsole.log('Fit mode:', grid.gridConfig.fitMode);console.log('Columns:', grid.gridConfig.columns?.length);fitMode
Section titled “fitMode”Get or set the column sizing mode.
'stretch'(default): Columns stretch to fill available width'fixed': Columns use explicit widths; horizontal scroll if needed'auto': Columns auto-size to content on initial render
fitMode: FitModeExample
Section titled “Example”// Use fixed widths with horizontal scrollgrid.fitMode = 'fixed';
// Stretch columns to fill containergrid.fitMode = 'stretch';
// Auto-size columns based on contentgrid.fitMode = 'auto';getConfig()
Section titled “getConfig()”Get a frozen snapshot of the current effective configuration. The returned object is read-only and reflects all merged config sources.
getConfig(): Promise<Readonly<GridConfig<T>>>Returns
Section titled “Returns”Promise<Readonly<GridConfig<T>>> - Promise resolving to frozen configuration object
Example
Section titled “Example”const config = await grid.getConfig();console.log('Columns:', config.columns?.length);console.log('Fit mode:', config.fitMode);Lifecycle
Section titled “Lifecycle”ready()
Section titled “ready()”Wait for the grid to be ready. Resolves once the component has finished initial setup, including column inference, plugin initialization, and first render.
ready(): Promise<void>Returns
Section titled “Returns”Promise<void> - Promise that resolves when the grid is ready
Example
Section titled “Example”const grid = queryGrid('tbw-grid');await grid.ready();console.log('Grid is ready, rows:', grid.rows.length);forceLayout()
Section titled “forceLayout()”Force a full layout/render cycle. Use this after programmatic changes that require re-measurement, such as container resize or dynamic style changes.
forceLayout(): Promise<void>Returns
Section titled “Returns”Promise<void> - Promise that resolves when the render cycle completes
Example
Section titled “Example”// After resizing the containercontainer.style.width = '800px';await grid.forceLayout();console.log('Grid re-rendered');suspendProcessing()
Section titled “suspendProcessing()”⚠️ Deprecated: This method is a no-op. Use insertRow or removeRow instead, which correctly preserve the current sort/filter view while adding or removing individual rows. Will be removed in v2.
Suspend row processing for the next rows update.
suspendProcessing(): voidData Management
Section titled “Data Management”getRowId()
Section titled “getRowId()”Get the unique ID for a row.
Uses the configured getRowId function or falls back to row.id / row._id.
getRowId(row: T): stringParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
row | T | The row object |
Returns
Section titled “Returns”string - The row’s unique identifier
Example
Section titled “Example”const id = grid.getRowId(row);console.log('Row ID:', id);getRow()
Section titled “getRow()”Get a row by its ID. O(1) lookup via internal Map.
getRow(id: string): T | undefinedParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
id | string | Row identifier (from getRowId) |
Returns
Section titled “Returns”T | undefined - The row object, or undefined if not found
Example
Section titled “Example”const row = grid.getRow('cargo-123');if (row) { console.log('Found:', row.name);}updateRow()
Section titled “updateRow()”Update a row by ID.
Mutates the row in-place and emits cell-change for each changed field.
updateRow(id: string, changes: Partial<T>, source: UpdateSource): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
id | string | Row identifier (from getRowId) |
changes | Partial<T> | Partial row data to merge |
source | UpdateSource | Origin of update (default: ‘api’) |
Events
Section titled “Events”| Event | Description |
|---|---|
cell-change | For each field that changed |
Example
Section titled “Example”// WebSocket update handlersocket.on('cargo-update', (data) => { grid.updateRow(data.id, { status: data.status, eta: data.eta });});updateRows()
Section titled “updateRows()”Batch update multiple rows.
More efficient than multiple updateRow() calls - single render cycle.
updateRows(updates: object[], source: UpdateSource): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
updates | object[] | Array of { id, changes } objects |
source | UpdateSource | Origin of updates (default: ‘api’) |
Events
Section titled “Events”| Event | Description |
|---|---|
cell-change | For each field that changed on each row |
Example
Section titled “Example”// Bulk status updategrid.updateRows([ { id: 'cargo-1', changes: { status: 'shipped' } }, { id: 'cargo-2', changes: { status: 'shipped' } },]);insertRow()
Section titled “insertRow()”Insert a row at a specific position in the current view.
The row is spliced into the visible (processed) row array at index and
appended to the source data so that future pipeline runs (sort, filter,
group) include it. No plugin processing is triggered — the row stays
exactly where you place it until the next full pipeline run.
By default, an 'insert' animation is applied. Pass animate: false to
skip the animation. The returned Promise resolves when the animation
completes (or immediately when animate is false).
insertRow(index: number, row: T, animate: boolean): Promise<void>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
index | number | Visible row index at which to insert (0-based) |
row | T | The row data object to insert |
animate | boolean | Whether to apply an ‘insert’ animation (default: true) |
Example
Section titled “Example”// Insert with animation (default)grid.insertRow(3, { id: nextId(), name: '', status: 'Draft' });
// Insert without animationgrid.insertRow(3, newRow, false);
// Await animation completionawait grid.insertRow(3, newRow);removeRow()
Section titled “removeRow()”Remove a row at a specific position in the current view.
The row is removed from both the visible (processed) row array and the source data. No plugin processing is triggered — remaining rows keep their current positions until the next full pipeline run.
By default, a 'remove' animation plays before the row is removed.
Pass animate: false to remove immediately. When animated, await the
result to ensure the row has been fully removed from data.
removeRow(index: number, animate: boolean): Promise<T | undefined>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
index | number | Visible row index to remove (0-based) |
animate | boolean | Whether to apply a ‘remove’ animation first (default: true) |
Returns
Section titled “Returns”Promise<T | undefined> - The removed row object, or undefined if index was out of range
Example
Section titled “Example”// Remove with fade-out animation (default)await grid.removeRow(5);
// Remove immediately, no animationconst removed = await grid.removeRow(5, false);Column Visibility
Section titled “Column Visibility”setColumnVisible()
Section titled “setColumnVisible()”Show or hide a column by field name.
setColumnVisible(field: string, visible: boolean): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
field | string | The field name of the column to modify |
visible | boolean | Whether the column should be visible |
Returns
Section titled “Returns”boolean - true if the visibility changed, false if unchanged
Events
Section titled “Events”| Event | Description |
|---|---|
column-state-change | Emitted when the visibility changes |
Example
Section titled “Example”// Hide the email columngrid.setColumnVisible('email', false);
// Show it againgrid.setColumnVisible('email', true);toggleColumnVisibility()
Section titled “toggleColumnVisibility()”Toggle a column’s visibility.
toggleColumnVisibility(field: string): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
field | string | The field name of the column to toggle |
Returns
Section titled “Returns”boolean - The new visibility state (true = visible, false = hidden)
Events
Section titled “Events”| Event | Description |
|---|---|
column-state-change | Emitted when the visibility changes |
Example
Section titled “Example”// Toggle the notes column visibilityconst isNowVisible = grid.toggleColumnVisibility('notes');console.log(`Notes column is now ${isNowVisible ? 'visible' : 'hidden'}`);isColumnVisible()
Section titled “isColumnVisible()”Check if a column is currently visible.
isColumnVisible(field: string): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
field | string | The field name to check |
Returns
Section titled “Returns”boolean - true if the column is visible, false if hidden
Example
Section titled “Example”if (grid.isColumnVisible('email')) { console.log('Email column is showing');}showAllColumns()
Section titled “showAllColumns()”Show all columns, resetting any hidden columns to visible.
showAllColumns(): voidEvents
Section titled “Events”| Event | Description |
|---|---|
column-state-change | Emitted when column visibility changes |
Example
Section titled “Example”// Reset button handlerresetButton.onclick = () => grid.showAllColumns();getAllColumns()
Section titled “getAllColumns()”Get metadata for all columns including visibility state. Useful for building a column picker UI.
getAllColumns(): object[]Returns
Section titled “Returns”object[] - Array of column info objects
Example
Section titled “Example”// Build a column visibility menuconst columns = grid.getAllColumns();columns.forEach(col => { if (!col.utility) { // Skip utility columns like selection checkbox const menuItem = document.createElement('label'); menuItem.innerHTML = ` <input type="checkbox" ${col.visible ? 'checked' : ''}> ${col.header} `; menuItem.querySelector('input').onchange = () => grid.toggleColumnVisibility(col.field); menu.appendChild(menuItem); }});Column Order
Section titled “Column Order”setColumnOrder()
Section titled “setColumnOrder()”Set the display order of columns.
setColumnOrder(order: string[]): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
order | string[] | Array of field names in desired order |
Events
Section titled “Events”| Event | Description |
|---|---|
column-state-change | Emitted when column order changes |
Example
Section titled “Example”// Move 'status' column to first positionconst currentOrder = grid.getColumnOrder();const newOrder = ['status', ...currentOrder.filter(f => f !== 'status')];grid.setColumnOrder(newOrder);getColumnOrder()
Section titled “getColumnOrder()”Get the current column display order.
getColumnOrder(): string[]Returns
Section titled “Returns”string[] - Array of field names in display order
Example
Section titled “Example”const order = grid.getColumnOrder();console.log('Columns:', order.join(', '));State Persistence
Section titled “State Persistence”columnState
Section titled “columnState”Get the current column state.
Alias for getColumnState() for property-style access.
columnState: GridColumnState | undefinedgetColumnState()
Section titled “getColumnState()”Get the current column state for persistence. Returns a serializable object including column order, widths, visibility, sort state, and any plugin-specific state.
Use this to save user preferences to localStorage or a database.
getColumnState(): GridColumnStateReturns
Section titled “Returns”GridColumnState - Serializable column state object
Example
Section titled “Example”// Save state to localStorageconst state = grid.getColumnState();localStorage.setItem('gridState', JSON.stringify(state));
// Later, restore the stateconst saved = localStorage.getItem('gridState');if (saved) { grid.columnState = JSON.parse(saved);}resetColumnState()
Section titled “resetColumnState()”Reset column state to initial configuration. Clears all user modifications including order, widths, visibility, and sort.
resetColumnState(): voidEvents
Section titled “Events”| Event | Description |
|---|---|
column-state-change | Emitted after state is reset |
Example
Section titled “Example”// Reset button handlerresetBtn.onclick = () => { grid.resetColumnState(); localStorage.removeItem('gridState');};Tool Panel
Section titled “Tool Panel”isToolPanelOpen
Section titled “isToolPanelOpen”Check if the tool panel sidebar is currently open.
The tool panel is an accordion-based sidebar that contains sections
registered by plugins or via registerToolPanel().
readonly isToolPanelOpen: booleanExample
Section titled “Example”// Conditionally show/hide a "toggle panel" buttonconst isPanelOpen = grid.isToolPanelOpen;toggleButton.textContent = isPanelOpen ? 'Close Panel' : 'Open Panel';expandedToolPanelSections
Section titled “expandedToolPanelSections”Get the IDs of currently expanded accordion sections in the tool panel.
Multiple sections can be expanded simultaneously in the accordion view.
readonly expandedToolPanelSections: string[]Example
Section titled “Example”// Check which sections are expandedconst expanded = grid.expandedToolPanelSections;console.log('Expanded sections:', expanded);// e.g., ['columnVisibility', 'filtering']openToolPanel()
Section titled “openToolPanel()”Open the tool panel sidebar.
The tool panel displays an accordion view with all registered panel sections. Each section can be expanded/collapsed independently.
openToolPanel(): voidExample
Section titled “Example”// Open the tool panel when a toolbar button is clickedsettingsButton.addEventListener('click', () => { grid.openToolPanel();});closeToolPanel()
Section titled “closeToolPanel()”Close the tool panel sidebar.
closeToolPanel(): voidExample
Section titled “Example”// Close the panel after user makes a selectiongrid.closeToolPanel();toggleToolPanel()
Section titled “toggleToolPanel()”Toggle the tool panel sidebar open or closed.
toggleToolPanel(): voidExample
Section titled “Example”// Wire up a toggle buttontoggleButton.addEventListener('click', () => { grid.toggleToolPanel();});toggleToolPanelSection()
Section titled “toggleToolPanelSection()”Toggle an accordion section expanded or collapsed within the tool panel.
toggleToolPanelSection(sectionId: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
sectionId | string | The ID of the section to toggle (matches ToolPanelDefinition.id) |
Example
Section titled “Example”// Expand the column visibility section programmaticallygrid.openToolPanel();grid.toggleToolPanelSection('columnVisibility');getToolPanels()
Section titled “getToolPanels()”Get all registered tool panel definitions.
Returns both plugin-registered panels and panels registered via registerToolPanel().
getToolPanels(): ToolPanelDefinition[]Returns
Section titled “Returns”ToolPanelDefinition[] - Array of tool panel definitions
Example
Section titled “Example”// List all available panelsconst panels = grid.getToolPanels();panels.forEach(panel => { console.log(`Panel: ${panel.title} (${panel.id})`);});registerToolPanel()
Section titled “registerToolPanel()”Register a custom tool panel section.
Use this API to add custom UI sections to the tool panel sidebar without creating a full plugin. The panel will appear as an accordion section in the tool panel.
registerToolPanel(panel: ToolPanelDefinition): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
panel | ToolPanelDefinition | The tool panel definition |
Example
Section titled “Example”// Register a custom "Export" panelgrid.registerToolPanel({ id: 'export', title: 'Export Options', icon: '📥', order: 50, // Lower order = higher in list render: (container) => { container.innerHTML = ` <button id="export-csv">Export CSV</button> <button id="export-json">Export JSON</button> `; container.querySelector('#export-csv')?.addEventListener('click', () => { exportToCSV(grid.rows); }); }});unregisterToolPanel()
Section titled “unregisterToolPanel()”Unregister a custom tool panel section.
unregisterToolPanel(panelId: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
panelId | string | The ID of the panel to remove |
Example
Section titled “Example”// Remove the export panel when no longer neededgrid.unregisterToolPanel('export');Header Content
Section titled “Header Content”getHeaderContents()
Section titled “getHeaderContents()”Get all registered header content definitions.
getHeaderContents(): HeaderContentDefinition[]Returns
Section titled “Returns”HeaderContentDefinition[] - Array of header content definitions
Example
Section titled “Example”const contents = grid.getHeaderContents();console.log('Header sections:', contents.map(c => c.id));registerHeaderContent()
Section titled “registerHeaderContent()”Register custom header content.
Header content appears in the grid’s header bar area, which is displayed above the column headers. Use this for search boxes, filters, or other controls that should be prominently visible.
registerHeaderContent(content: HeaderContentDefinition): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
content | HeaderContentDefinition | The header content definition |
Example
Section titled “Example”// Add a global search box to the headergrid.registerHeaderContent({ id: 'global-search', order: 10, render: (container) => { const input = document.createElement('input'); input.type = 'search'; input.placeholder = 'Search all columns...'; input.addEventListener('input', (e) => { const term = (e.target as HTMLInputElement).value; filterGrid(term); }); container.appendChild(input); }});unregisterHeaderContent()
Section titled “unregisterHeaderContent()”Unregister custom header content.
unregisterHeaderContent(contentId: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
contentId | string | The ID of the content to remove |
Example
Section titled “Example”grid.unregisterHeaderContent('global-search');Toolbar
Section titled “Toolbar”getToolbarContents()
Section titled “getToolbarContents()”Get all registered toolbar content definitions.
getToolbarContents(): ToolbarContentDefinition[]Returns
Section titled “Returns”ToolbarContentDefinition[] - Array of toolbar content definitions
Example
Section titled “Example”const contents = grid.getToolbarContents();console.log('Toolbar items:', contents.map(c => c.id));registerToolbarContent()
Section titled “registerToolbarContent()”Register custom toolbar content.
Toolbar content appears in the grid’s toolbar area. Use this for action
buttons, dropdowns, or other controls that should be easily accessible.
Content is rendered in order of the order property (lower = first).
registerToolbarContent(content: ToolbarContentDefinition): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
content | ToolbarContentDefinition | The toolbar content definition |
Example
Section titled “Example”// Add export buttons to the toolbargrid.registerToolbarContent({ id: 'export-buttons', order: 100, // Position in toolbar (lower = first) render: (container) => { const csvBtn = document.createElement('button'); csvBtn.textContent = 'Export CSV'; csvBtn.className = 'tbw-toolbar-btn'; csvBtn.addEventListener('click', () => exportToCSV(grid.rows));
const jsonBtn = document.createElement('button'); jsonBtn.textContent = 'Export JSON'; jsonBtn.className = 'tbw-toolbar-btn'; jsonBtn.addEventListener('click', () => exportToJSON(grid.rows));
container.append(csvBtn, jsonBtn); }});unregisterToolbarContent()
Section titled “unregisterToolbarContent()”Unregister custom toolbar content.
unregisterToolbarContent(contentId: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
contentId | string | The ID of the content to remove |
Example
Section titled “Example”// Remove export buttons when switching to read-only modegrid.unregisterToolbarContent('export-buttons');Custom Styles
Section titled “Custom Styles”registerStyles()
Section titled “registerStyles()”Register custom CSS styles to be injected into the grid’s shadow DOM. Use this to style custom cell renderers, editors, or detail panels.
Uses adoptedStyleSheets for efficiency - styles survive shadow DOM rebuilds.
registerStyles(id: string, css: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
id | string | Unique identifier for the style block (for removal/updates) |
css | string | CSS string to inject |
Example
Section titled “Example”// Register custom styles for a detail panelgrid.registerStyles('my-detail-styles', ` .my-detail-panel { padding: 16px; } .my-detail-table { width: 100%; }`);
// Update styles latergrid.registerStyles('my-detail-styles', updatedCss);
// Remove stylesgrid.unregisterStyles('my-detail-styles');unregisterStyles()
Section titled “unregisterStyles()”Remove previously registered custom styles.
unregisterStyles(id: string): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
id | string | The ID used when registering the styles |
getRegisteredStyles()
Section titled “getRegisteredStyles()”Get list of registered custom style IDs.
getRegisteredStyles(): string[]Plugin Communication
Section titled “Plugin Communication”getPlugin()
Section titled “getPlugin()”Get a plugin instance by its class constructor.
Prefer getPluginByName for most use cases — it avoids importing the plugin class and returns the actual instance registered in the grid.
getPlugin(PluginClass: (args: any[]) => P): P | undefinedParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
PluginClass | (args: any[]) => P | The plugin class (constructor) to look up. |
Returns
Section titled “Returns”P | undefined - The plugin instance, or undefined if not registered.
Example
Section titled “Example”// Preferred: by name (no import needed)const selection = grid.getPluginByName('selection');
// Alternative: by class (requires import)import { SelectionPlugin } from '@toolbox-web/grid/plugins/selection';const selection = grid.getPlugin(SelectionPlugin);selection?.selectAll();getPluginByName()
Section titled “getPluginByName()”Get a plugin instance by its string name. Useful for loose coupling when you don’t want to import the plugin class (e.g., in framework adapters or dynamic scenarios).
getPluginByName(name: K): unknown | undefinedParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
name | K | The plugin name (matches BaseGridPlugin.name). |
Returns
Section titled “Returns”unknown | undefined - The plugin instance, or undefined if not registered.
Example
Section titled “Example”const editing = grid.getPluginByName('editing');Row Animation
Section titled “Row Animation”animateRow()
Section titled “animateRow()”Animate a row at the specified index.
Applies a visual animation to highlight changes, insertions, or removals.
Returns a Promise that resolves when the animation completes.
Animation types:
'change': Flash highlight (for data changes, e.g., after cell edit)'insert': Slide-in animation (for newly added rows)'remove': Fade-out animation (for rows being removed)
The animation is purely visual - it does not affect the data. For remove animations, the row remains in the DOM until animation completes.
animateRow(rowIndex: number, type: RowAnimationType): Promise<boolean>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowIndex | number | Index of the row in the current row set |
type | RowAnimationType | Type of animation to apply |
Returns
Section titled “Returns”Promise<boolean> - true if the row was found and animated, false otherwise
Example
Section titled “Example”// Highlight a row and wait for the animation to finishawait grid.animateRow(rowIndex, 'change');
// Fire-and-forget (animation runs in background)grid.animateRow(rowIndex, 'insert');animateRows()
Section titled “animateRows()”Animate multiple rows at once.
More efficient than calling animateRow() multiple times.
Returns a Promise that resolves when all animations complete.
animateRows(rowIndices: number[], type: RowAnimationType): Promise<number>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowIndices | number[] | Indices of the rows to animate |
type | RowAnimationType | Type of animation to apply to all rows |
Returns
Section titled “Returns”Promise<number> - Number of rows that were actually animated (visible in viewport)
Example
Section titled “Example”// Highlight all changed rows after bulk updateconst changedIndices = [0, 2, 5];await grid.animateRows(changedIndices, 'change');animateRowById()
Section titled “animateRowById()”Animate a row by its ID.
Uses the configured getRowId function to find the row.
Returns a Promise that resolves when the animation completes.
animateRowById(rowId: string, type: RowAnimationType): Promise<boolean>Parameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier (from getRowId) |
type | RowAnimationType | Type of animation to apply |
Returns
Section titled “Returns”Promise<boolean> - true if the row was found and animated, false otherwise
Example
Section titled “Example”// Highlight a row after real-time updatesocket.on('row-updated', async (data) => { grid.updateRow(data.id, data.changes); await grid.animateRowById(data.id, 'change');});Focus & Navigation
Section titled “Focus & Navigation”focusedCell
Section titled “focusedCell”The currently focused cell position, or null if no rows are loaded.
Returns a snapshot object with the row index, visible column index, and the field name of the focused column.
readonly focusedCell: object | nullExample
Section titled “Example”const cell = grid.focusedCell;if (cell) { console.log(`Focused on row ${cell.rowIndex}, column "${cell.field}"`);}focusCell()
Section titled “focusCell()”Move focus to a specific cell.
Accepts a column index (into the visible columns array) or a field name. The grid scrolls the cell into view and applies focus styling.
focusCell(rowIndex: number, column: string | number): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowIndex | number | The row index to focus (0-based, in the current processed row array) |
column | string | number | Column index (0-based into visible columns) or field name string |
Example
Section titled “Example”// Focus by column indexgrid.focusCell(0, 2);
// Focus by field namegrid.focusCell(5, 'email');scrollToRow()
Section titled “scrollToRow()”Scroll the viewport so a row is visible.
Uses the grid’s internal virtualization state (row height, position cache) to calculate the correct scroll offset, including support for variable row heights and grouped rows.
scrollToRow(rowIndex: number, options: ScrollToRowOptions): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowIndex | number | Row index (0-based, in the current processed row array) |
options | ScrollToRowOptions | Alignment and scroll behavior |
Example
Section titled “Example”// Scroll to row, only if not already visiblegrid.scrollToRow(42);
// Center the row in the viewport with smooth scrollinggrid.scrollToRow(42, { align: 'center', behavior: 'smooth' });scrollToRowById()
Section titled “scrollToRowById()”Scroll the viewport so a row is visible, identified by its unique ID.
Uses getRowId (or the fallback row.id / row._id)
to find the row in the current (possibly sorted/filtered) data, then delegates
to scrollToRow.
scrollToRowById(rowId: string, options: ScrollToRowOptions): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier |
options | ScrollToRowOptions | Alignment and scroll behavior |
Example
Section titled “Example”// After inserting a row, scroll to it by IDgrid.scrollToRowById('emp-42', { align: 'center' });Virtualization
Section titled “Virtualization”defaultRowHeight
Section titled “defaultRowHeight”The default row height in pixels.
For fixed heights, this is the configured or CSS-measured row height. For variable heights, this is the average/estimated row height. Plugins should use this instead of hardcoding row heights.
readonly defaultRowHeight: numberFocus Management
Section titled “Focus Management”registerExternalFocusContainer()
Section titled “registerExternalFocusContainer()”Register an external DOM element as a logical focus container of this grid.
Focus moving into a registered container is treated as if it stayed inside
the grid: data-has-focus is preserved, click-outside commit is suppressed,
and the editing focus trap (when enabled) won’t reclaim focus.
Typical use case: overlay panels (datepickers, dropdowns, autocompletes)
that render at <body> level to escape grid overflow clipping.
registerExternalFocusContainer(el: Element): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
el | Element | The external element to register |
Example
Section titled “Example”const overlay = document.createElement('div');document.body.appendChild(overlay);
// Tell the grid this overlay is "part of" the gridgrid.registerExternalFocusContainer(overlay);
// Later, when overlay is removedgrid.unregisterExternalFocusContainer(overlay);unregisterExternalFocusContainer()
Section titled “unregisterExternalFocusContainer()”Unregister a previously registered external focus container.
unregisterExternalFocusContainer(el: Element): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
el | Element | The element to unregister |
containsFocus()
Section titled “containsFocus()”Check whether focus is logically inside this grid.
Returns true when document.activeElement (or the given node) is
inside the grid’s own DOM or inside any element registered via
registerExternalFocusContainer.
containsFocus(node: Node | null): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
node | Node | unknown | Optional node to test. Defaults to document.activeElement. |
Example
Section titled “Example”if (grid.containsFocus()) { console.log('Grid or one of its overlays has focus');}Accessors
Section titled “Accessors”loading
Section titled “loading”Whether the grid is currently in a loading state. When true, displays a loading overlay with spinner (or custom loadingRenderer).
loading: booleanExample
Section titled “Example”grid.loading = true;const data = await fetchData();grid.rows = data;grid.loading = false;Methods
Section titled “Methods”setRowLoading()
Section titled “setRowLoading()”Set loading state for a specific row. Shows a small spinner indicator on the row.
setRowLoading(rowId: string, loading: boolean): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier (from getRowId) |
loading | boolean | Whether the row is loading |
Example
Section titled “Example”// Show loading while saving row datagrid.setRowLoading('row-123', true);await saveRow(rowData);grid.setRowLoading('row-123', false);setCellLoading()
Section titled “setCellLoading()”Set loading state for a specific cell. Shows a small spinner indicator on the cell.
setCellLoading(rowId: string, field: string, loading: boolean): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier |
field | string | The column field |
loading | boolean | Whether the cell is loading |
Example
Section titled “Example”// Show loading while validating a single fieldgrid.setCellLoading('row-123', 'email', true);const valid = await validateEmail(newValue);grid.setCellLoading('row-123', 'email', false);isRowLoading()
Section titled “isRowLoading()”Check if a row is currently in loading state.
isRowLoading(rowId: string): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier |
isCellLoading()
Section titled “isCellLoading()”Check if a cell is currently in loading state.
isCellLoading(rowId: string, field: string): booleanParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowId | string | The row’s unique identifier |
field | string | The column field |
clearAllLoading()
Section titled “clearAllLoading()”Clear all row and cell loading states.
clearAllLoading(): voidaddEventListener()
Section titled “addEventListener()”Add a typed event listener for grid events.
This override provides type-safe event handling for DataGrid-specific events. The event detail is automatically typed based on the event name.
Prefer grid.on() for most use cases — it auto-unwraps the detail payload and returns an unsubscribe function for easy cleanup.
Use addEventListener when you need standard DOM options like once,
capture, passive, or signal (AbortController).
addEventListener(type: K, listener: (this: DataGridElement<T>, ev: CustomEvent<unknown>) => void, options: boolean | AddEventListenerOptions): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
type | K | |
listener | (this: DataGridElement<T>, ev: CustomEvent<unknown>) => void | |
options | boolean | AddEventListenerOptions |
Example
Section titled “Example”// Recommended: use grid.on() insteadconst off = grid.on('cell-click', (detail) => { console.log(detail.field, detail.value);});
// addEventListener is useful when you need DOM listener optionsgrid.addEventListener('cell-click', (e) => { console.log(e.detail.field, e.detail.value);}, { once: true });
// Or with AbortController for batch cleanupconst controller = new AbortController();grid.addEventListener('sort-change', (e) => { fetchData({ sortBy: e.detail.field });}, { signal: controller.signal });controller.abort(); // removes all listeners tied to this signalremoveEventListener()
Section titled “removeEventListener()”Remove a typed event listener for grid events.
removeEventListener(type: K, listener: (this: DataGridElement<T>, ev: CustomEvent<unknown>) => void, options: boolean | EventListenerOptions): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
type | K | |
listener | (this: DataGridElement<T>, ev: CustomEvent<unknown>) => void | |
options | boolean | EventListenerOptions |
Subscribe to a typed grid event. Recommended over addEventListener.
Returns an unsubscribe function — call it to remove the listener.
The listener receives the event detail as its first argument
(no need to dig into e.detail), and the raw CustomEvent as
the second argument when you need preventDefault() or stopPropagation().
on(type: K, listener: (detail: unknown, event: CustomEvent<unknown>) => void): () => voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
type | K | |
listener | (detail: unknown, event: CustomEvent<unknown>) => void |
Example
Section titled “Example”// Basic usage — detail is auto-unwrappedconst off = grid.on('cell-click', ({ row, field, value }) => { console.log(`Clicked ${field} = ${value}`);});
// Clean up when doneoff();invalidateRowHeight()
Section titled “invalidateRowHeight()”Invalidate a row’s height in the position cache. Call this when a plugin changes a row’s height (e.g., expanding/collapsing a detail panel).
invalidateRowHeight(rowIndex: number, newHeight: number): voidParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
rowIndex | number | Index of the row whose height changed |
newHeight | number | Optional new height. If not provided, queries plugins for height. |