### Clone Example Project Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-operations-graphql Clone the example project repository to get started. ```bash git clone https://github.com/ag-grid/ag-grid-server-side-graphql-example.git ``` -------------------------------- ### AG-Grid Setup with Value Parser Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/value-parsers This TypeScript example demonstrates a full AG-Grid setup including registering modules, defining column definitions with a `valueParser` for number conversion, and initializing the grid. ```typescript import { CellValueChangedEvent, ClientSideRowModelModule, GridApi, GridOptions, ModuleRegistry, TextEditorModule, ValidationModule, ValueParserParams, createGrid, } from "ag-grid-community"; import { getData } from "./data"; ModuleRegistry.registerModules([ TextEditorModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ { headerName: "Name", field: "simple" }, { headerName: "Bad Number", field: "numberBad" }, { headerName: "Good Number", field: "numberGood", valueParser: numberParser, }, ], defaultColDef: { flex: 1, editable: true, cellDataType: false, }, rowData: getData(), onCellValueChanged: onCellValueChanged, }; function onCellValueChanged(event: CellValueChangedEvent) { console.log("data after changes is: ", event.data); } function numberParser(params: ValueParserParams) { return Number(params.newValue); } const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); ``` -------------------------------- ### Complete AG Grid Example with TypeScript Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid A full example demonstrating AG Grid setup with TypeScript, including module registration, row data interface, grid API, and grid options. Use this as a starting point for complex grids. ```typescript import { AllCommunityModule, GridApi, GridOptions, ModuleRegistry, createGrid, } from "ag-grid-community"; ModuleRegistry.registerModules([AllCommunityModule]); // Row Data Interface interface IRow { make: string; model: string; price: number; electric: boolean; } // Grid API: Access to Grid API methods let gridApi: GridApi; // Grid Options: Contains all of the grid configurations const gridOptions: GridOptions = { // Data to be displayed rowData: [ { make: "Tesla", model: "Model Y", price: 64950, electric: true }, { make: "Ford", model: "F-Series", price: 33850, electric: false }, { make: "Toyota", model: "Corolla", price: 29600, electric: false }, { make: "Mercedes", model: "EQA", price: 48890, electric: true }, { make: "Fiat", model: "500", price: 15774, electric: false }, { make: "Nissan", model: "Juke", price: 20675, electric: false }, ], // Columns to be displayed (Should match rowData properties) columnDefs: [ { field: "make" }, { field: "model" }, { field: "price" }, { field: "electric" }, ], defaultColDef: { flex: 1, }, }; // Create Grid: Create new grid within the #myGrid div, using the Grid Options object gridApi = createGrid( document.querySelector("#myGrid")!, gridOptions, ); ``` -------------------------------- ### Basic AG-Grid Setup with Theming Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/theming-v32-customisation-headers This snippet demonstrates a standard AG-Grid setup in TypeScript, including module registration and fetching data. Ensure 'ag-grid-community' is installed and the necessary CSS files are imported. ```typescript import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; import { ClientSideRowModelModule, GridApi, GridOptions, ModuleRegistry, NumberEditorModule, NumberFilterModule, TextEditorModule, TextFilterModule, ValidationModule, createGrid, } from "ag-grid-community"; import { IOlympicData } from "./interfaces"; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; ModuleRegistry.registerModules([ NumberEditorModule, TextEditorModule, TextFilterModule, NumberFilterModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { theme: "legacy", columnDefs: [ { headerName: "Group 1", children: [{ field: "athlete", minWidth: 170 }, { field: "age" }], }, { headerName: "Group 2", children: [ { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ], }, ], defaultColDef: { editable: true, filter: true, }, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); ``` -------------------------------- ### Full AG-Grid Setup with Pagination Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/deep-dive This example demonstrates a complete AG-Grid setup in TypeScript, including module registration, row data interface, column definitions, default column configurations, grid options with pagination enabled, and fetching remote data. ```typescript import { AllCommunityModule, GridApi, GridOptions, ModuleRegistry, createGrid, } from "ag-grid-community"; ModuleRegistry.registerModules([AllCommunityModule]); // Row Data Interface interface IRow { mission: string; company: string; location: string; date: string; time: string; rocket: string; price: number; successful: boolean; } // Grid API: Access to Grid API methods let gridApi: GridApi; // Grid Options: Contains all of the grid configurations const gridOptions: GridOptions = { // Data to be displayed rowData: [], // Columns to be displayed (Should match rowData properties) columnDefs: [ { field: "mission", filter: true }, { field: "company" }, { field: "location" }, { field: "date" }, { field: "price" }, { field: "successful" }, { field: "rocket" }, ], // Configurations applied to all columns defaultColDef: { filter: true, }, // Grid Options pagination: true, }; // Create Grid: Create new grid within the #myGrid div, using the Grid Options object gridApi = createGrid( document.querySelector("#myGrid")!, gridOptions, ); // Fetch Remote Data fetch("https://www.ag-grid.com/example-assets/space-mission-data.json") .then((response) => response.json()) .then((data: any) => gridApi.setGridOption("rowData", data)); ``` -------------------------------- ### Full AG-Grid Setup with Custom Column Types Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/column-definitions A complete TypeScript example demonstrating the setup of AG-Grid with custom column types, including module registration, data interfaces, value formatters, and grid configuration. ```typescript import { CellStyleModule, ClientSideRowModelModule, GridApi, GridOptions, ModuleRegistry, ValidationModule, ValueFormatterParams, createGrid, } from "ag-grid-community"; ModuleRegistry.registerModules([ CellStyleModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); interface SalesRecord { productName: string; boughtPrice: number; soldPrice: number; } function currencyFormatter(params: ValueFormatterParams) { const value = Math.floor(params.value); if (isNaN(value)) { return ""; } return "£" + value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"); } const gridOptions: GridOptions = { // define column types columnTypes: { currency: { width: 150, valueFormatter: currencyFormatter, }, shaded: { cellClass: "shaded-class", }, }, // define grid columns columnDefs: [ { field: "productName" }, // uses properties from currency type { field: "boughtPrice", type: "currency" }, // uses properties from currency AND shaded types { field: "soldPrice", type: ["currency", "shaded"] }, ], rowData: [ { productName: "Lamp", boughtPrice: 100, soldPrice: 200 }, { productName: "Chair", boughtPrice: 150, soldPrice: 300 }, { productName: "Desk", boughtPrice: 200, soldPrice: 400 }, ], }; const gridDiv = document.querySelector("#myGrid")!; const gridApi = createGrid(gridDiv, gridOptions); ``` -------------------------------- ### Run the Application Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-operations-graphql Start the application server from the command line. ```bash yarn start ``` -------------------------------- ### Clone AG Grid Server-Side Oracle Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-operations-oracle Clone the example project from GitHub to get started with the AG Grid Server-Side Row Model and Oracle integration. ```bash git clone https://github.com/ag-grid/ag-grid-server-side-oracle-example.git ``` -------------------------------- ### Initialize Grid with Value Cache Off Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/value-cache Starts the data grid with the value cache feature turned off. This is the initial setup call for the example. ```javascript onValueCache(false); ``` -------------------------------- ### AG-Grid Setup with Modules and Data Fetching Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/theming-v32-customisation-tool-panels This example demonstrates setting up AG-Grid with essential modules and fetching data from a remote source. Ensure all required modules are registered before creating the grid. ```typescript import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; import { ClientSideRowModelModule, ColDef, GridApi, GridOptions, ModuleRegistry, NumberEditorModule, NumberFilterModule, TextEditorModule, ValidationModule, createGrid, } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, FiltersToolPanelModule, PivotModule, SetFilterModule, } from "ag-grid-enterprise"; import { IOlympicData } from "./interfaces"; ModuleRegistry.registerModules([ NumberEditorModule, TextEditorModule, NumberFilterModule, ClientSideRowModelModule, ColumnsToolPanelModule, FiltersToolPanelModule, ColumnMenuModule, ContextMenuModule, PivotModule, SetFilterModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); const columnDefs: ColDef[] = [ { field: "athlete", minWidth: 170 }, { field: "age" }, { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { theme: "legacy", rowData: null, columnDefs: columnDefs, defaultColDef: { editable: true, filter: true, enableRowGroup: true, enablePivot: true, enableValue: true, }, sideBar: true, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); ``` -------------------------------- ### Server-Side Datasource Setup Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-model-changing-columns Sets up the server-side datasource by fetching data and initializing the fake server and grid. ```javascript var fakeServer: any = undefined; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then(function (data) { // setup the fake server with entire dataset fakeServer = new FakeServer(data); // create datasource with a reference to the fake server const datasource: IServerSideDatasource = getServerSideDatasource(fakeServer); // register the datasource with the grid gridApi!.setGridOption("serverSideDatasource", datasource); }); if (typeof window !== "undefined") { // Attach external event handlers to window so they can be called from index.html (window).onBtApply = onBtApply; } ``` -------------------------------- ### Database Setup Script Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-operations-graphql Import the SQL script to create and populate the 'sample_data' database and 'olympic_winners' table. ```bash mysql -u root -p -D sample_data < ./data/olympic_winners.sql ``` -------------------------------- ### Master / Detail Setup with Modules and Data Fetching Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/master-detail Set up the AG-Grid with Master / Detail module and fetch data. This example demonstrates module registration, grid initialization, and data loading. ```typescript import { ClientSideRowModelModule, FirstDataRenderedEvent, GridApi, GridOptions, IDetailCellRendererParams, ModuleRegistry, RowApiModule, ValidationModule, createGrid, } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, MasterDetailModule, } from "ag-grid-enterprise"; import { IAccount } from "./interfaces"; ModuleRegistry.registerModules([ RowApiModule, ClientSideRowModelModule, ColumnsToolPanelModule, MasterDetailModule, ColumnMenuModule, ContextMenuModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ // group cell renderer needed for expand / collapse icons { field: "name", cellRenderer: "agGroupCellRenderer" }, { field: "account" }, { field: "calls" }, { field: "minutes", valueFormatter: "x.toLocaleString() + 'm'" }, ], defaultColDef: { flex: 1, }, masterDetail: true, detailCellRendererParams: { detailGridOptions: { columnDefs: [ { field: "callId" }, { field: "direction" }, { field: "number", minWidth: 150 }, { field: "duration", valueFormatter: "x.toLocaleString() + 's'" }, { field: "switchCode", minWidth: 150 }, ], defaultColDef: { flex: 1, }, }, getDetailRowData: (params) => { params.successCallback(params.data.callRecords); }, } as IDetailCellRendererParams, onFirstDataRendered: onFirstDataRendered, }; function onFirstDataRendered(params: FirstDataRenderedEvent) { // arbitrarily expand a row for presentational purposes setTimeout(() => { params.api.getDisplayedRowAtIndex(1)!.setExpanded(true); }, 0); } const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/master-detail-data.json") .then((response) => response.json()) .then((data: IAccount[]) => { gridApi!.setGridOption("rowData", data); }); ``` -------------------------------- ### Example: Accessing Individual Filters Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/filter-api Demonstrates how to get a reference to the 'athlete' filter instance and interact with its methods, such as getting and setting the mini filter text. ```APIDOC ## Example: Accessing Individual Filters ### Description This example shows how to interact with an individual filter instance, using the Set Filter as an example. It covers getting the mini filter text, saving it, and restoring it. ### Code Example ```typescript // Get a reference to the 'name' filter UI instance const filterInstance = await api.getColumnFilterInstance('name'); // Example functions demonstrating interaction with Set Filter function getMiniFilterText() { gridApi! \ .getColumnFilterInstance('athlete') \ .then((athleteFilter) => { console.log(athleteFilter!.getMiniFilter()); }); } function saveMiniFilterText() { gridApi! \ .getColumnFilterInstance('athlete') \ .then((athleteFilter) => { savedMiniFilterText = athleteFilter!.getMiniFilter(); }); } function restoreMiniFilterText() { gridApi! \ .getColumnFilterInstance('athlete') \ .then((athleteFilter) => { athleteFilter!.setMiniFilter(savedMiniFilterText); }); } ``` ``` -------------------------------- ### AG-Grid Tree Data Transactions Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-model-tree-data This is the main TypeScript example for demonstrating transactions with Tree Data. It includes grid setup, data handling, and transaction logic. ```TypeScript import { ColDef, GetRowIdParams, GridApi, GridOptions, IRowNode, IServerSideDatasource, IServerSideGetRowsParams, IServerSideGetRowsRequest, IsServerSideGroupOpenByDefaultParams, ModuleRegistry, TextFilterModule, ValidationModule, createGrid, } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, ServerSideRowModelApiModule, ServerSideRowModelModule, TreeDataModule, } from "ag-grid-enterprise"; ModuleRegistry.registerModules([ TextFilterModule, ColumnsToolPanelModule, ColumnMenuModule, ContextMenuModule, TreeDataModule, ServerSideRowModelModule, ServerSideRowModelApiModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let fakeServer: { getData: (request: IServerSideGetRowsRequest) => void; addChildRow: (route: string[], newRow: any) => void; toggleEmployment: (route: string[]) => void; removeEmployee: (route: string[]) => void; moveEmployee: (from: string[], to: string[]) => void; }; const columnDefs: ColDef[] = [ { field: "employeeId", hide: true }, { field: "employeeName", hide: true }, { field: "employmentType" }, { field: "startDate" }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { defaultColDef: { width: 235, flex: 1, sortable: false, }, autoGroupColumnDef: { field: "employeeName", }, rowModelType: "serverSide", treeData: true, columnDefs, cacheBlockSize: 10, rowSelection: { mode: "singleRow" }, isServerSideGroupOpenByDefault: ( params: IsServerSideGroupOpenByDefaultParams, ) => { const isKathrynPowers = params.rowNode.level == 0 && params.data.employeeName == "Kathryn Powers"; const isMabelWard = params.rowNode.level == 1 && params.data.employeeName == "Mabel Ward"; return isKathrynPowers || isMabelWard; }, getRowId: (row: GetRowIdParams) => String(row.data.employeeId), isServerSideGroup: (dataItem: any) => dataItem.group, getServerSideGroupKey: (dataItem: any) => dataItem.employeeName, }; function getRouteToNode(rowNode: IRowNode): string[] { if (!rowNode.parent) { return []; } return [ ...getRouteToNode(rowNode.parent), rowNode.key ? rowNode.key : rowNode.data.employeeName, ]; } let latestId = 100000; function addToSelected() { const selected = gridApi!.getSelectedNodes()[0]; if (!selected) { console.log("No row was selected."); return; } const route = getRouteToNode(selected); const newRow = { employeeId: ++latestId, employeeName: "Bertrand Parker " + latestId, employmentType: "Permanent", startDate: "20/01/1999", }; fakeServer.addChildRow(route, newRow); } function updateSelected() { const selected = gridApi!.getSelectedNodes()[0]; if (!selected) { console.log("No row was selected."); return; } const route = getRouteToNode(selected); fakeServer.toggleEmployment(route); } function deleteSelected() { const selected = gridApi!.getSelectedNodes()[0]; if (!selected) { console.log("No row was selected."); return; } const route = getRouteToNode(selected); fakeServer.removeEmployee(route); } function moveSelected() { const selected = gridApi!.getSelectedNodes()[0]; if (!selected) { console.log("No row was selected."); return; } const route = getRouteToNode(selected); fakeServer.moveEmployee(route, ["Robert Peterson"]); } const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/tree-data.json") .then((response) => response.json()) .then(function (data) { const adjustedData = [ { employeeId: -1, employeeName: "Robert Peterson", employmentType: "Founder", startDate: "24/01/1990", }, ...data, ]; const fakeServer = createFakeServer(adjustedData, gridApi!) const datasource = createServerSideDatasource(fakeServer); gridApi!.setGridOption("serverSideDatasource", datasource); }); function createFakeServer(fakeServerData: any[], api: GridApi) { const getDataAtRoute = (route: string[]) => { let mutableRoute = [...route]; let target: any = { underlings: fakeServerData }; ``` -------------------------------- ### AG-Grid Setup and Data Fetching in JavaScript Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/keyboard-navigation Demonstrates how to create an AG-Grid instance, define column definitions and grid options, and fetch data from a JSON endpoint to populate the grid. Ensure the grid container element exists and the necessary AG-Grid library is imported. ```javascript const columnDefs = [ { field: "athlete", }, { field: "country", flex: 1, cellRenderer: CustomElements, }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs, defaultColDef: { minWidth: 130, suppressKeyboardEvent, }, }; // Setup the grid after the page has finished loading const gridDiv = document.querySelector("#myGrid")!; // Ensure #myGrid element exists gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/small-olympic-winners.json") .then((response) => response.json()) .then((data) => { gridApi!.setGridOption("rowData", data); }); ``` -------------------------------- ### AG-Grid Setup with Row Selection Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/theming-v32-customisation-selections Basic AG-Grid setup with row selection enabled. Ensure the RowSelectionModule is registered. This example fetches data and sets up a grid with multi-row selection. ```typescript import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; import { ClientSideRowModelModule, ColDef, GridApi, GridOptions, ModuleRegistry, NumberEditorModule, NumberFilterModule, RowSelectionModule, TextEditorModule, TextFilterModule, ValidationModule, createGrid, } from "ag-grid-community"; import { IOlympicData } from "./interfaces"; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; ModuleRegistry.registerModules([ NumberEditorModule, TextEditorModule, TextFilterModule, NumberFilterModule, RowSelectionModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); const columnDefs: ColDef[] = [ { field: "athlete", minWidth: 170 }, { field: "age" }, { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { theme: "legacy", columnDefs: columnDefs, rowSelection: { mode: "multiRow" }, defaultColDef: { editable: true, filter: true, }, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); ``` -------------------------------- ### Full Line Sparkline Configuration Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/sparklines-line-customisation This TypeScript example demonstrates how to configure ag-Grid with custom Line Sparkline options, including imports, module registration, and grid setup. ```typescript import { AgChartsCommunityModule, AgSparklineOptions, } from "ag-charts-community"; import { ClientSideRowModelModule, GridApi, GridOptions, ModuleRegistry, ValidationModule, createGrid, } from "ag-grid-community"; import { ClipboardModule, ContextMenuModule, SparklinesModule, } from "ag-grid-enterprise"; import { getData } from "./data"; ModuleRegistry.registerModules([ ClientSideRowModelModule, SparklinesModule.with(AgChartsCommunityModule), ClipboardModule, ContextMenuModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ { field: "symbol", maxWidth: 120 }, { field: "name", minWidth: 250 }, { field: "change", cellRenderer: "agSparklineCellRenderer", cellRendererParams: { sparklineOptions: { type: "line", stroke: "rgb(124, 255, 178)", strokeWidth: 2, marker: { enabled: true, size: 0, itemStyler: (params: any) => { if (params.highlightState === "highlighted-item") { return { size: 7, }; } }, }, highlight: { highlightedItem: { fill: "rgb(124, 255, 178)", strokeWidth: 0, }, }, padding: { top: 5, bottom: 5, }, } as AgSparklineOptions, }, }, { field: "volume", maxWidth: 140, }, ], defaultColDef: { flex: 1, minWidth: 100, }, rowData: getData(), rowHeight: 50, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); ``` -------------------------------- ### AG-Grid Setup with Custom Theme and Data Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/theming-distribution This example demonstrates a full AG-Grid setup in TypeScript, including module registration, defining column definitions, generating row data, configuring grid options with a custom theme, and initializing the grid. Ensure `AllCommunityModule` is registered and the target element exists. ```typescript import { AllCommunityModule, ColDef, GridOptions, ModuleRegistry, colorSchemeVariable, createGrid, createTheme, iconSetMaterial, } from "ag-grid-community"; import { IOlympicData } from "./interfaces"; ModuleRegistry.registerModules([AllCommunityModule]); const myCustomTheme = createTheme() // add just the parts you want .withPart(iconSetMaterial) .withPart(colorSchemeVariable) // set default param values .withParams({ accentColor: "red", iconSize: 18, }); const columnDefs: ColDef[] = [ { field: "make" }, { field: "model" }, { field: "price" }, ]; const rowData: any[] = (() => { const rowData: any[] = []; for (let i = 0; i < 10; i++) { rowData.push({ make: "Toyota", model: "Celica", price: 35000 + i * 1000 }); rowData.push({ make: "Ford", model: "Mondeo", price: 32000 + i * 1000 }); rowData.push({ make: "Porsche", model: "Boxster", price: 72000 + i * 1000, }); } return rowData; })(); const gridOptions: GridOptions = { theme: myCustomTheme, columnDefs, rowData, defaultColDef: { editable: true, flex: 1, minWidth: 100, filter: true, }, rowSelection: { mode: "multiRow", checkboxes: true }, }; createGrid(document.querySelector("#myGrid")!, gridOptions); ``` -------------------------------- ### AG-Grid Row Copying Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/clipboard This example demonstrates how to enable and toggle the `copySelectedRows` functionality. It includes setup for AG-Grid with necessary modules and event handlers for toggling the copy behavior. ```typescript import { ClientSideRowModelModule, GridApi, GridOptions, ModuleRegistry, NumberEditorModule, RowSelectionModule, TextEditorModule, ValidationModule, createGrid, } from "ag-grid-community"; import { CellSelectionModule, ClipboardModule, ColumnMenuModule, ContextMenuModule, } from "ag-grid-enterprise"; import { IOlympicData } from "./interfaces"; ModuleRegistry.registerModules([ NumberEditorModule, TextEditorModule, ClientSideRowModelModule, ClipboardModule, ColumnMenuModule, ContextMenuModule, CellSelectionModule, RowSelectionModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ { field: "athlete", minWidth: 200 }, { field: "age" }, { field: "country", minWidth: 150 }, { field: "year" }, { field: "date", minWidth: 150 }, { field: "sport", minWidth: 150 }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ], defaultColDef: { editable: true, flex: 1, minWidth: 100, }, rowSelection: { mode: "multiRow", copySelectedRows: false, }, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); function toggleCopyRows() { gridApi.setGridOption("rowSelection", { mode: "multiRow", copySelectedRows: document.querySelector("#toggle-copy-rows")?.checked ?? false, }); } if (typeof window !== "undefined") { // Attach external event handlers to window so they can be called from index.html (window).toggleCopyRows = toggleCopyRows; } ``` -------------------------------- ### AG-Grid Setup with Time Series Charting Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/integrated-charts-time-series This example demonstrates setting up AG-Grid with enterprise modules, configuring column definitions for time series data, and defining chart theme overrides for a time axis. It includes event handlers for grid readiness and data rendering to create a chart. ```typescript import { AgChartsEnterpriseModule } from "ag-charts-enterprise"; import { ClientSideRowModelModule, FirstDataRenderedEvent, GridApi, GridOptions, GridReadyEvent, ModuleRegistry, ValidationModule, createGrid, } from "ag-grid-community"; import { ColumnMenuModule, ContextMenuModule, IntegratedChartsModule, RowGroupingModule, } from "ag-grid-enterprise"; import { getData } from "./data"; ModuleRegistry.registerModules([ ClientSideRowModelModule, IntegratedChartsModule.with(AgChartsEnterpriseModule), ColumnMenuModule, ContextMenuModule, RowGroupingModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ { field: "timestamp", chartDataType: "time" }, { field: "cpuUsage" }, ], defaultColDef: { flex: 1 }, cellSelection: true, popupParent: document.body, enableCharts: true, chartThemeOverrides: { area: { title: { enabled: true, text: "CPU Usage", }, navigator: { enabled: true, height: 20, spacing: 25, }, axes: { time: { label: { rotation: 315, format: "%H:%M", }, }, number: { label: { formatter: (params: any) => { // charts typings return params.value + "%"; }, }, }, }, }, }, chartToolPanelsDef: { panels: ["data", "format"], }, onGridReady: (params: GridReadyEvent) => { getData().then((rowData) => params.api.setGridOption("rowData", rowData)); }, onFirstDataRendered, }; function onFirstDataRendered(params: FirstDataRenderedEvent) { params.api.createRangeChart({ chartContainer: document.querySelector("#myChart") as HTMLElement, cellRange: { columns: ["timestamp", "cpuUsage"], }, suppressChartRanges: true, chartType: "area", }); } function formatTime(date: Date | number) { return Intl.DateTimeFormat("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit", }).format(new Date(date)); } gridApi = createGrid( document.querySelector("#myGrid")!, gridOptions, ); ``` -------------------------------- ### Ag-Grid Master Detail Example with Fixed Height Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/master-detail-height A comprehensive TypeScript example demonstrating the master-detail setup with a fixed `detailRowHeight` of 200. It includes necessary module registrations and data fetching. ```typescript import { ClientSideRowModelModule, FirstDataRenderedEvent, GridApi, GridOptions, IDetailCellRendererParams, ModuleRegistry, RowApiModule, ValidationModule, createGrid, } from "ag-grid-community"; import { ColumnMenuModule, ColumnsToolPanelModule, ContextMenuModule, MasterDetailModule, } from "ag-grid-enterprise"; import { IAccount } from "./interfaces"; ModuleRegistry.registerModules([ RowApiModule, ClientSideRowModelModule, ColumnsToolPanelModule, MasterDetailModule, ColumnMenuModule, ContextMenuModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); let gridApi: GridApi; const gridOptions: GridOptions = { columnDefs: [ // group cell renderer needed for expand / collapse icons { field: "name", cellRenderer: "agGroupCellRenderer" }, { field: "account" }, { field: "calls" }, { field: "minutes", valueFormatter: "x.toLocaleString() + 'm'" }, ], defaultColDef: { flex: 1, }, masterDetail: true, detailRowHeight: 200, detailCellRendererParams: { detailGridOptions: { columnDefs: [ { field: "callId" }, { field: "direction" }, { field: "number", minWidth: 150 }, { field: "duration", valueFormatter: "x.toLocaleString() + 's'" }, { field: "switchCode", minWidth: 150 }, ], defaultColDef: { flex: 1, }, }, getDetailRowData: (params) => { params.successCallback(params.data.callRecords); }, } as IDetailCellRendererParams, alwaysShowVerticalScroll: true, onFirstDataRendered: onFirstDataRendered, }; function onFirstDataRendered(params: FirstDataRenderedEvent) { // arbitrarily expand a row for presentational purposes setTimeout(() => { params.api.getDisplayedRowAtIndex(1)!.setExpanded(true); }, 0); } const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/master-detail-data.json") .then((response) => response.json()) .then((data: IAccount[]) => { gridApi!.setGridOption("rowData", data); }); ``` -------------------------------- ### Full AG Grid JavaScript Data Grid Example Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/getting-started A complete example demonstrating the setup, instantiation, and configuration of the AG Grid JavaScript Data Grid using TypeScript and modules. ```typescript import { AllCommunityModule, GridApi, GridOptions, ModuleRegistry, createGrid, } from "ag-grid-community"; ModuleRegistry.registerModules([AllCommunityModule]); // Row Data Interface interface IRow { make: string; model: string; price: number; electric: boolean; } // Grid API: Access to Grid API methods let gridApi: GridApi; // Grid Options: Contains all of the grid configurations const gridOptions: GridOptions = { // Data to be displayed rowData: [ { make: "Tesla", model: "Model Y", price: 64950, electric: true }, { make: "Ford", model: "F-Series", price: 33850, electric: false }, { make: "Toyota", model: "Corolla", price: 29600, electric: false }, { make: "Mercedes", model: "EQA", price: 48890, electric: true }, { make: "Fiat", model: "500", price: 15774, electric: false }, { make: "Nissan", model: "Juke", price: 20675, electric: false }, ], // Columns to be displayed (Should match rowData properties) columnDefs: [ { field: "make" }, { field: "model" }, { field: "price" }, { field: "electric" }, ], defaultColDef: { flex: 1, }, }; // Create Grid: Create new grid within the #myGrid div, using the Grid Options object gridApi = createGrid( document.querySelector("#myGrid")!, gridOptions, ); ``` -------------------------------- ### Install Project Dependencies and Build Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/server-side-operations-spark Install project dependencies and build the project using Maven. ```bash mvn clean install ``` -------------------------------- ### Custom Row Drag Start Pixels Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/row-dragging-customisation Configure the number of pixels a row must be dragged before the drag event officially starts. This example sets the threshold to 0px, initiating drag on mousedown. ```TypeScript import { CellStyleModule, ClientSideRowModelModule, ColDef, GridApi, GridOptions, ModuleRegistry, NumberFilterModule, RowDragCancelEvent, RowDragEndEvent, RowDragEnterEvent, RowDragModule, TextFilterModule, ValidationModule, createGrid, } from "ag-grid-community"; import { CustomCellRenderer } from "./customCellRenderer"; import { IOlympicData } from "./interfaces"; ModuleRegistry.registerModules([ TextFilterModule, NumberFilterModule, RowDragModule, CellStyleModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); const columnDefs: ColDef[] = [ { field: "athlete", cellClass: "custom-athlete-cell", cellRenderer: CustomCellRenderer, }, { field: "country" }, { field: "year", width: 100 }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { defaultColDef: { width: 170, filter: true, }, rowDragManaged: true, columnDefs: columnDefs, onRowDragEnter: onRowDragEnter, onRowDragEnd: onRowDragEnd, onRowDragCancel: onRowDragCancel, }; function onRowDragEnter(e: RowDragEnterEvent) { console.log("onRowDragEnter", e); } function onRowDragEnd(e: RowDragEndEvent) { console.log("onRowDragEnd", e); } function onRowDragCancel(e: RowDragCancelEvent) { console.log("onRowDragCancel", e); } const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); ``` -------------------------------- ### AG-Grid Setup with Quartz Theme Source: https://www.ag-grid.com/archive/35.0.0/javascript-data-grid/theming-v32-customisation-colours Initialize AG-Grid with the Quartz theme, registering necessary modules and configuring columns. This example fetches data from a remote URL to populate the grid. ```typescript import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; import { ClientSideRowModelModule, ColDef, GridApi, GridOptions, ModuleRegistry, NumberEditorModule, NumberFilterModule, TextEditorModule, TextFilterModule, ValidationModule, createGrid, } from "ag-grid-community"; import { IOlympicData } from "./interfaces"; import "ag-grid-community/styles/ag-grid.css"; import "ag-grid-community/styles/ag-theme-quartz.css"; ModuleRegistry.registerModules([ NumberEditorModule, TextEditorModule, TextFilterModule, NumberFilterModule, ClientSideRowModelModule, ...(process.env.NODE_ENV !== "production" ? [ValidationModule] : []), ]); const columnDefs: ColDef[] = [ { field: "athlete", minWidth: 170 }, { field: "age" }, { field: "country" }, { field: "year" }, { field: "date" }, { field: "sport" }, { field: "gold" }, { field: "silver" }, { field: "bronze" }, { field: "total" }, ]; let gridApi: GridApi; const gridOptions: GridOptions = { theme: "legacy", columnDefs: columnDefs, defaultColDef: { editable: true, filter: true, }, }; const gridDiv = document.querySelector("#myGrid")!; gridApi = createGrid(gridDiv, gridOptions); fetch("https://www.ag-grid.com/example-assets/olympic-winners.json") .then((response) => response.json()) .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data)); ```