This section shows how the Grid API can be used to save and restore charts.
Saving / Restoring Charts Copy Link
The example below demonstrates how you can save and then later restore a chart. You can make changes to the chart type, theme, data and formatting options and note how the restored chart looks the same as the chart that was saved.
- Change the chart type, theme, data and/or formatting in order to see the changes restored later.
- Click "Save chart" to persist a model of the visible chart into a local variable.
- Click "Clear chart" to destroy the existing chart.
- Click "Restore chart" to restore the previously saved chart.
"use client";
import React, {
useCallback,
useMemo,
useRef,
useState,
useEffect,
StrictMode,
} from "react";
import { createRoot } from "react-dom/client";
import { AgGridReact, AgGridProvider } from "ag-grid-react";
import "./styles.css";
import { AgChartsEnterpriseModule } from "ag-charts-enterprise";
import {
CellSelectionOptions,
ChartModel,
ChartRef,
ClientSideRowModelModule,
ColDef,
ColGroupDef,
CreateChartContainer,
FirstDataRenderedEvent,
GridApi,
GridOptions,
GridReadyEvent,
ModuleRegistry,
NumberEditorModule,
TextEditorModule,
TextFilterModule,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ContextMenuModule,
IntegratedChartsModule,
RowGroupingModule,
} from "ag-grid-enterprise";
import { getData } from "./data";
if (process.env.NODE_ENV !== "production") {
// Enable extended validations only for development
enableDevValidations();
}
const modules = [
TextEditorModule,
TextFilterModule,
NumberEditorModule,
ClientSideRowModelModule,
IntegratedChartsModule.with(AgChartsEnterpriseModule),
ColumnMenuModule,
ContextMenuModule,
RowGroupingModule,
];
let chartModel: ChartModel | undefined;
let currentChartRef: ChartRef | undefined;
const GridExample = () => {
const gridRef = useRef<AgGridReact>(null);
const containerStyle = useMemo(() => ({ width: "100%", height: "100%" }), []);
const gridStyle = useMemo(() => ({ height: "100%", width: "100%" }), []);
const [rowData, setRowData] = useState<any[]>();
const [columnDefs, setColumnDefs] = useState<ColDef[]>([
{ field: "country", chartDataType: "category" },
{ field: "sugar", chartDataType: "series" },
{ field: "fat", chartDataType: "series" },
{ field: "weight", chartDataType: "series" },
]);
const defaultColDef = useMemo<ColDef>(() => {
return {
editable: true,
flex: 1,
minWidth: 100,
filter: true,
};
}, []);
const popupParent = useMemo<HTMLElement | null>(() => {
return document.body;
}, []);
const onGridReady = useCallback((params: GridReadyEvent) => {
getData().then((rowData) => setRowData(rowData));
}, []);
const onFirstDataRendered = useCallback((params: FirstDataRenderedEvent) => {
currentChartRef = params.api.createRangeChart({
chartContainer: document.querySelector("#myChart") as any,
cellRange: {
columns: ["country", "sugar", "fat", "weight"],
rowStartIndex: 0,
rowEndIndex: 2,
},
chartType: "groupedColumn",
});
}, []);
const saveChart = useCallback(() => {
const chartModels = gridRef.current!.api.getChartModels() || [];
if (chartModels.length > 0) {
chartModel = chartModels[0];
}
}, []);
const clearChart = useCallback(() => {
if (currentChartRef) {
currentChartRef.destroyChart();
currentChartRef = undefined;
}
}, [currentChartRef]);
const restoreChart = useCallback(() => {
if (!chartModel) return;
currentChartRef = gridRef.current!.api.restoreChart(chartModel)!;
}, [chartModel]);
const createChartContainer = useCallback(
(chartRef: ChartRef) => {
if (currentChartRef) {
currentChartRef.destroyChart();
}
const eChart = chartRef.chartElement;
const eParent = document.querySelector<HTMLElement>("#myChart")!;
eParent.appendChild(eChart);
currentChartRef = chartRef;
},
[currentChartRef],
);
return (
<AgGridProvider modules={modules}>
<div style={containerStyle}>
<div className="wrapper">
<div id="buttons">
<button onClick={saveChart}>Save chart</button>
<button onClick={clearChart}>Clear chart</button>
<button onClick={restoreChart}>Restore chart</button>
</div>
<div id="myGrid" style={gridStyle}>
<AgGridReact
ref={gridRef}
rowData={rowData}
columnDefs={columnDefs}
defaultColDef={defaultColDef}
cellSelection={true}
popupParent={popupParent}
enableCharts={true}
createChartContainer={createChartContainer}
onGridReady={onGridReady}
onFirstDataRendered={onFirstDataRendered}
/>
</div>
<div id="myChart" className="my-chart"></div>
</div>
</div>
</AgGridProvider>
);
};
const root = createRoot(document.getElementById("root")!);
root.render(
<StrictMode>
<GridExample />
</StrictMode>,
);
.wrapper {
display: flex;
flex-direction: column;
height: 100%;
}
#myGrid {
flex: 1;
}
.my-chart {
flex: 1;
}
#buttons {
padding-bottom: 10px;
}
export async function getData(delay: number = 100): Promise<any[]> {
return new Promise((resolve) => setTimeout(() => resolve(generateData()), delay));
}
function generateData(): any[] {
const countries = [
'Ireland',
'Spain',
'United Kingdom',
'France',
'Germany',
'Luxembourg',
'Sweden',
'Norway',
'Italy',
'Greece',
'Iceland',
'Portugal',
'Malta',
'Brazil',
'Argentina',
'Colombia',
'Peru',
'Venezuela',
'Uruguay',
'Belgium',
];
return countries.map((country) => ({
country,
sugar: getRandomNumber(0, 50),
fat: getRandomNumber(0, 100),
weight: getRandomNumber(0, 200),
}));
}
function getRandomNumber(min: number, max: number): number {
return Math.floor(window.agRandom() * (max - min + 1)) + min;
}
API Reference Copy Link
A chart model that represent all the state information about the rendered charts can be obtained using getChartModels(). These models are returned in a format that can be easily used with the other API methods to later restore the chart.
Returns a list of models with information about the charts that are currently rendered from the grid. |
Properties available on the ChartModel interface.
string |
ChartModelType |
string |
ChartType |
CellRangeParams |
string |
AgChartThemeOverrides |
AgChartThemePalette |
boolean |
boolean |
string | IAggFunc |
boolean |
SeriesChartType[] |
SeriesGroupType |
boolean |
These models can then be supplied to the following grid api method to restore the charts:
Restores a chart using the ChartModel that was previously obtained from getChartModels(). |
Note that an optional chartContainer can be specified when restoring a chart.