How to persist and restore the grid's original state
Problem discussion
Whenever an enablePersistence property has been enabled, Grid will retain its state in the page reload. In some cases, user might be required to retain initial state of the Grid. Since the persistence property has been enabled, Grid will not retain its initial state.
Solution
To overcome the discussed problem, we can save the initial properties of the Grid in a private variable and later, set them to the Grid using the setProperties method. In this KB, we have demonstrated this scenario using the button click event.
Place the Grid and button element
Declare the Grid element along with the button (used for restoring the initial value).
<input id='btn' type="button" value="Set Data" /> <div id="Grids"></div>
Define the Grid
Define the Grid properties with the dataBound event, where you have to collect initial properties of the Grid.
let grid: Grid = new Grid({ dataSource: inventoryData, allowPaging: true, allowSorting: true, allowFiltering: true, enablePersistence: true, height: 400, columns: [ { field: 'Inventor', headerText: 'Inventor Name', width: 160 }, { field: 'NumberofPatentFamilies', headerText: 'No of Patent Families', width: 195, textAlign: 'Right' }, { field: 'Country', headerText: 'Country', width: 120 }, { field: 'Active', headerText: 'Active', width: 120 }, { field: 'Mainfieldsofinvention', headerText: 'Main fields of invention', allowGrouping: false, width: 200 }, ], pageSettings: { pageCount: 5 }, dataBound: onDatabound }); grid.appendTo('#Grids');
Define the databound event of the Grid
The initialRender property acts as flag variable in the dataBound event and it will avoid the recursive call of the setProperties method.
let initialRender = true; let onDatabound = () => {
if (initialRender) { gridProperties = JSON.parse(grid.getPersistData()); initialRender = false; } } let gridProperties; |
Define the click event to restore Grid state
Use the setProperties method of the Grid to restore the initial state with the saved gridProperties value.
document.querySelector('input').addEventListener('click', (e) => { grid.setProperties(gridProperties);
}) |
Output
Figure 1: Grid with the retained state
Typescript demo: https://stackblitz.com/edit/3i3a7w-ohf2h9?file=index.ts
Angular demo: https://stackblitz.com/edit/persist-grid?file=app.component.ts
React Demo: https://stackblitz.com/edit/perist-react-grid?file=index.js