Documentation Index
Fetch the complete documentation index at: https://mintlify.com/ag-grid/ag-grid/llms.txt
Use this file to discover all available pages before exploring further.
The Grid API provides methods to interact with and control your grid programmatically. Access it through the GridApi object returned when creating the grid or via the api property in event callbacks.
Overview
The Grid API is your main interface for controlling the grid after itβs initialized:
import { createGrid, GridApi, GridOptions } from 'ag-grid-community';
const gridOptions: GridOptions = {
columnDefs: [...],
rowData: [...]
};
const gridDiv = document.querySelector('#myGrid');
const api: GridApi = createGrid(gridDiv, gridOptions);
// Use the API
api.sizeColumnsToFit();
Accessing the API
At Grid Creation
const api = createGrid(gridDiv, gridOptions);
In Event Handlers
const gridOptions: GridOptions = {
onGridReady: (params) => {
// Access via event params
params.api.sizeColumnsToFit();
},
onCellClicked: (event) => {
// Available in all grid events
event.api.deselectAll();
}
};
In Framework Components
import { useRef } from 'react';
import { AgGridReact } from 'ag-grid-react';
import { GridApi } from 'ag-grid-community';
function MyGrid() {
const gridRef = useRef<AgGridReact>(null);
const handleClick = () => {
gridRef.current?.api.exportDataAsCsv();
};
return (
<>
<button onClick={handleClick}>Export</button>
<AgGridReact ref={gridRef} {...gridOptions} />
</>
);
}
Core Methods
Grid Lifecycle
Destroy the grid and release resources. Required when using vanilla JavaScript.// Clean up when done
api.destroy();
Check if the grid has been destroyed.if (!api.isDestroyed()) {
api.refreshCells();
}
Grid Options
getGridOption(key)
<Key extends keyof GridOptions>(key: Key) => GridOptions[Key]
Get the current value of a grid option.const pageSize = api.getGridOption('paginationPageSize');
const rowData = api.getGridOption('rowData');
setGridOption(key, value)
<Key extends ManagedGridOptionKey>(key: Key, value: GridOptions[Key]) => void
Update a single grid option.api.setGridOption('paginationPageSize', 50);
api.setGridOption('rowHeight', 40);
updateGridOptions(options)
(options: GridOptions) => void
Update multiple grid options at once (recommended over multiple setGridOption calls).api.updateGridOptions({
paginationPageSize: 50,
rowHeight: 40,
animateRows: true
});
Row Data Methods
Transactions
applyTransaction(transaction)
(transaction: RowDataTransaction) => RowNodeTransaction | null
Add, remove, or update rows efficiently.const result = api.applyTransaction({
add: [{ id: 1, name: 'New Row' }],
update: [{ id: 2, name: 'Updated' }],
remove: [oldRow]
});
applyTransactionAsync(transaction, callback?)
(transaction: RowDataTransaction, callback?: (res: RowNodeTransaction) => void) => void
Queue a transaction for async execution. Grid batches multiple async transactions for efficiency.// Queue updates
api.applyTransactionAsync({ add: [row1] });
api.applyTransactionAsync({ add: [row2] });
// Grid batches these automatically
Execute all queued async transactions immediately.api.applyTransactionAsync({ add: [row1] });
api.applyTransactionAsync({ add: [row2] });
api.flushAsyncTransactions(); // Execute now
Row Access
forEachNode(callback)
(callback: (rowNode: IRowNode, index: number) => void) => void
Iterate through all row nodes (ignoring filtering/sorting).const allData: any[] = [];
api.forEachNode(node => {
allData.push(node.data);
});
forEachNodeAfterFilterAndSort(callback)
(callback: (rowNode: IRowNode, index: number) => void) => void
Iterate through displayed rows (after filtering and sorting).const displayedData: any[] = [];
api.forEachNodeAfterFilterAndSort(node => {
displayedData.push(node.data);
});
getRowNode(id)
(id: string) => IRowNode | undefined
Get a specific row node by its ID.const rowNode = api.getRowNode('123');
if (rowNode) {
console.log('Row data:', rowNode.data);
}
Get the total number of displayed rows.const count = api.getDisplayedRowCount();
console.log(`Showing ${count} rows`);
Column Methods
Column Definitions
getColumnDefs()
(ColDef | ColGroupDef)[] | undefined
Get current column definitions.const currentCols = api.getColumnDefs();
getColumnDef(key)
(key: string | Column) => ColDef | null
Get the column definition for a specific column.const colDef = api.getColumnDef('athlete');
Column Visibility
setColumnsVisible(keys, visible)
(keys: (string | Column)[], visible: boolean) => void
Show or hide columns.// Hide columns
api.setColumnsVisible(['id', 'internal'], false);
// Show columns
api.setColumnsVisible(['name', 'email'], true);
Column Sizing
sizeColumnsToFit(params?)
(params?: ISizeColumnsToFitParams) => void
Size columns to fit the available grid width.
autoSizeColumns(keys, skipHeader?)
(keys: ColKey[] | ISizeColumnsToContentParams, skipHeader?: boolean) => void
Auto-size specific columns based on content.// Auto-size by column keys
api.autoSizeColumns(['athlete', 'country']);
// With options
api.autoSizeColumns({
columns: ['athlete', 'country'],
skipHeader: false
});
autoSizeAllColumns(skipHeader?)
(skipHeader?: boolean) => void
Auto-size all columns.api.autoSizeAllColumns();
Column State
Get current column state (width, position, sort, etc).const columnState = api.getColumnState();
localStorage.setItem('gridColumns', JSON.stringify(columnState));
applyColumnState(params)
(params: ApplyColumnStateParams) => boolean
Restore column state.const savedState = JSON.parse(localStorage.getItem('gridColumns'));
api.applyColumnState({ state: savedState });
Selection Methods
selectAll(mode?, source?)
(mode?: SelectAllMode, source?: SelectionEventSourceType) => void
Select all rows.api.selectAll(); // All rows
api.selectAll('filtered'); // Only filtered rows
api.selectAll('currentPage'); // Only current page
deselectAll(mode?, source?)
(mode?: SelectAllMode, source?: SelectionEventSourceType) => void
Get selected row nodes.const selectedNodes = api.getSelectedNodes();
console.log(`Selected ${selectedNodes.length} rows`);
Get selected row data.const selectedData = api.getSelectedRows();
console.log('Selected:', selectedData);
Filtering Methods
Check if any filter is active.if (api.isAnyFilterPresent()) {
console.log('Filters are active');
}
Get the current filter state.const filterState = api.getFilterModel();
localStorage.setItem('filters', JSON.stringify(filterState));
setFilterModel(model)
(model: FilterModel | null) => void
Set filter state.// Apply filters
api.setFilterModel({
athlete: {
filterType: 'text',
type: 'contains',
filter: 'Michael'
}
});
// Clear all filters
api.setFilterModel(null);
onFilterChanged(source?)
(source?: FilterChangedEventSourceType) => void
Notify grid that filters have changed (triggers re-filtering).
Refresh Methods
refreshCells(params?)
(params?: RefreshCellsParams) => void
Refresh specific cells.// Refresh all cells
api.refreshCells();
// Refresh specific columns
api.refreshCells({ columns: ['age', 'country'] });
// Refresh specific rows
api.refreshCells({ rowNodes: [rowNode1, rowNode2] });
// Force refresh (re-render)
api.refreshCells({ force: true });
redrawRows(params?)
(params?: RedrawRowsParams) => void
Completely redraw rows (removes and recreates DOM).// Redraw all rows
api.redrawRows();
// Redraw specific rows
api.redrawRows({ rowNodes: [rowNode1, rowNode2] });
Export Methods
exportDataAsCsv(params?)
(params?: CsvExportParams) => void
Export grid data as CSV.api.exportDataAsCsv({
fileName: 'export.csv',
columnKeys: ['athlete', 'age', 'country']
});
exportDataAsExcel(params?)
(params?: ExcelExportParams) => void
Export grid data as Excel (Enterprise only).api.exportDataAsExcel({
fileName: 'export.xlsx',
sheetName: 'Athletes'
});
Editing Methods
startEditingCell(params)
(params: StartEditingCellParams) => void
Start editing a specific cell.api.startEditingCell({
rowIndex: 0,
colKey: 'athlete'
});
stopEditing(cancel?)
(cancel?: boolean) => void
Stop editing.api.stopEditing(); // Save changes
api.stopEditing(true); // Cancel changes
Common Patterns
Save and Restore Grid State
// Save state
function saveGridState() {
const state = {
columns: api.getColumnState(),
filters: api.getFilterModel(),
sort: api.getColumnState().filter(col => col.sort != null)
};
localStorage.setItem('gridState', JSON.stringify(state));
}
// Restore state
function restoreGridState() {
const stateStr = localStorage.getItem('gridState');
if (stateStr) {
const state = JSON.parse(stateStr);
api.applyColumnState({ state: state.columns });
api.setFilterModel(state.filters);
}
}
// Hook up to events
const gridOptions: GridOptions = {
onGridReady: () => restoreGridState(),
onColumnMoved: () => saveGridState(),
onColumnResized: () => saveGridState(),
onSortChanged: () => saveGridState(),
onFilterChanged: () => saveGridState()
};
Export Filtered Data
function exportFiltered() {
if (api.isAnyFilterPresent()) {
api.exportDataAsCsv({
fileName: 'filtered-data.csv',
onlySelected: false,
skipPinnedTop: true,
skipPinnedBottom: true
});
} else {
alert('No filters applied');
}
}
Bulk Row Selection
function selectByCondition(predicate: (data: any) => boolean) {
api.forEachNode(node => {
if (predicate(node.data)) {
node.setSelected(true, false, 'api');
}
});
}
// Usage
selectByCondition(data => data.country === 'USA');
Auto-refresh Data
let intervalId: number;
function startAutoRefresh(intervalMs: number = 5000) {
intervalId = setInterval(async () => {
try {
const changes = await fetchDataChanges();
api.applyTransaction(changes);
} catch (error) {
console.error('Failed to refresh:', error);
}
}, intervalMs);
}
function stopAutoRefresh() {
clearInterval(intervalId);
}
// Start on grid ready
const gridOptions: GridOptions = {
onGridReady: () => startAutoRefresh(),
onGridPreDestroyed: () => stopAutoRefresh()
};
TypeScript Support
The API is fully typed. Use generics for type safety:
interface Athlete {
id: string;
athlete: string;
age: number;
country: string;
}
const api: GridApi<Athlete> = createGrid(gridDiv, gridOptions);
// TypeScript knows the type of data
api.forEachNode(node => {
const data: Athlete = node.data; // Typed!
console.log(data.athlete);
});
const selected: Athlete[] = api.getSelectedRows(); // Typed array
Best Practices
- Store the API reference - Keep a reference to use throughout your application
- Check isDestroyed() - Before calling API methods on long-lived references
- Use updateGridOptions() - Instead of multiple
setGridOption() calls
- Batch operations - Use transactions instead of multiple individual updates
- Leverage events - React to grid events instead of polling the API
- Type your data - Use TypeScript generics for better IDE support