How do I restore user defined charts in ag-grid?
I have implemented a save/restore feature in my web-app, which uses grid.api.getState()
to capture/save the grid state, and then a onLoad
function which sets the grid's initialState
to the saved states to restore it. It looks roughly like this:
<template>
<div>
<ag-grid-vue
v-if="gridVisible"
ref="gridRef"
rowModelType="clientSide"
:gridOptions="gridOptions"
:sideBar="['columns', 'filters']"
/>
</div>
<button onclick="onLoad">Load</button>
<button onclick="onSave">Save</button>
</template>
<script setup>
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-balham.css";
import { AgGridVue } from "ag-grid-vue3";
import {ref, reactive} from "vue"
const gridOptions = reactive({})
const gridVisible = ref(true)
var savedState = undefined
// ... some code to populate gridOptions with initial data
function onSave() {
savedState = gridRef.value.api.getState()
}
function onLoad() {
gridVisible.value = false;
// put the initialisation into the back of the ioservice so that the grid is
// disabled before we start
setTimeout(() => {
gridRef.value.api.gridOptions.initialState = state.gridState;
gridVisible.value = true;
});
}
</script>
This works for filters, grouping, column selections, etc. But if a user saves state with a user-defined chart in it, then saving/restoring this way causes the selected cells to be visible, but the chart itself disappears. How can I capture/restore the chart as well?
Update
As per David Glickman's response I've tried modifying my onSave
and onLoad
functions to include the getChartModels()
and restoreChart()
methods:
function onSave() {
savedState = {
grid: gridRef.value.api.getState(),
chart: gridRef.value.api.getChartModel()
}
function onLoad() {
gridVisible.value = false;
// put the initialisation into the back of the ioservice so that the grid is
// disabled before we start
setTimeout(() => {
gridRef.value.api.gridOptions.initialState = state.grid;
gridVisible.value = true;
if (state.chartState.length != 0) {
setTimeout(() => {
gridRef.value.api.restoreChart(state.chart);
});
}
});
}
However, when I do this I see no chart and a warning in the console:
ServerSideView.vue:73 AG Grid - unable to create chart as no range is selected.
Interestingly, the selection actually does restore, and I can see the cells that were selected when I did the save.
Answer
A chart model that represents all the state information about the rendered charts can be obtained using getChartModels()
. This returns a list of models with information about the charts that are currently rendered from the grid.
These models can then be supplied to the restoreChart
grid api method to restore the chart.
See https://www.ag-grid.com/javascript-data-grid/integrated-charts-api-save-restore-charts/ for more details.