State Management in EJ2 TypeScript Grid control

5 Jun 202424 minutes to read

State management in the EJ2 TypeScript Grid control allows you to maintain the grid’s state even after a browser refresh or when navigating to a different page within the same browser session. This feature is particularly useful for retaining the grid’s configuration and data even after a page reload.

To enable state persistence in the Grid, you can utilize the enablePersistence property. When this property is set to true, the grid will automatically save its state in the browser’s localStorage, ensuring that the state is preserved across page reloads.

let grid: Grid = new Grid({
    dataSource: data,
    enablePersistence: true,
});     
grid.appendTo('#Grid');

The grid will store the state using the combination of the control name and control ID in the storage. For example, if the control name is grid and the ID is OrderDetails, the state will be stored as gridOrderDetails.

When enabling state persistence, the following grid settings will persist in the local storage.

Grid Settings Properties persist Ignored properties
pageSettings currentPage
pageCount
pageSize
pageSizes
totalRecordsCount
template
enableQueryString
groupSettings allowReordering
columns
disablePageWiseAggregates
enableLazyLoading
showDropArea
showGroupedColumn
showToggleButton
showUngroupButton
captionTemplate
columns allowEditing
allowFiltering
allowGrouping
allowReordering
allowResizing
allowSearching
allowSorting
autoFit
disableHtmlEncode
enableGroupByFormat
field
foreignKeyField
index
showColumnMenu
showInColumnChooser
sortDirection
type
uid
visible
width
clipMode
commands
customAttributes
dataSource
defaultValue
displayAsCheckBox
edit
editTemplate
editType
filter
filterBarTemplate
filterTemplate
foreignKeyValue
format
formatter
freeze
headerTemplate
headerText
headerTextAlign
headerValueAccessor
hideAtMedia
isFrozen
isIdentity
isPrimaryKey
lockColumn
maxWidth
minWidth
sortComparer
template
textAlign
validationRules
valueAccessor
sortSettings - -
filterSettings - -
searchSettings - -
selectedRowIndex - -

The grid will persist only the last selected row index.

Restore initial Grid state

In the Syncfusion EJ2 TypeScript Grid control, you have the capability to restore the grid to its initial state, reverting all changes and configurations made during the interaction. This feature can be particularly useful when you want to reset the grid to its original settings, eliminating any applied filters, sorting, or column reordering.

Here are the steps to reset the grid to its initial state, even when the enablePersistence property is enabled:

Changing control id

If you want to restore the initial state of the grid, consider changing the control ID. This step ensures that the grid is treated as a new instance, effectively reverting to its default settings.

Here is an example code to change the control id dynamically to restore initial grid state.

import { Grid, Filter, Page} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject(Filter, Page);

let gridId = 'OrderDetails';
let grid: Grid = new Grid({
  dataSource: data,
  allowPaging: true,
  allowFiltering: true,
  enablePersistence: true,
  element: gridId,
  height: 300,
  columns: [
      { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
      { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
      { field: 'ShipCity', headerText: 'Ship City', width: 150 },
      { field: 'ShipName', headerText: 'Ship Name', width: 150 }
  ]
});
grid.appendTo('#Grid');

let restoreButton: Button = new Button({
  content: 'Restore to initial state',
});
restoreButton.appendTo('#restore');

(document.getElementById('restore')as HTMLElement).addEventListener('click', function () {
  gridId = 'OrderDetails' + Math.floor(Math.random() * 10);
  grid.element.id = gridId;
  location.reload();
});
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <button id="restore"></button>
        <div id='Grid'></div>        
    </div>
</body>
</html>

Clearing local storage

Another method to reset the grid is by clearing the local storage associated with the grid control. This action removes any stored state information, allowing the grid to return to its original configuration.

Here is an example code on how to clear local storage to retain its default state.

import { Grid, Filter, Page } from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject(Filter, Page);

let grid: Grid = new Grid({
    dataSource: data,
    enablePersistence: true,
    allowFiltering: true,
    allowPaging: true,
    columns: [
        { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
        { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
        { field: 'ShipCity', headerText: 'Ship City', width: 150 },
        { field: 'ShipName', headerText: 'Ship Name', width: 150 }
    ],
    height: 230
});
grid.appendTo('#Grid');

let restoreButton: Button = new Button({ cssClass: 'e-primary'});
restoreButton.appendTo('#restore');

(document.getElementById('restore')as HTMLElement).onclick = () => {
    grid.enablePersistence = false;
    window.localStorage.setItem("gridOrderDetails", ""); // Here grid is control name and OrderDetails is control ID
    grid.destroy();
    location.reload();
};
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <button id="restore">Restore to initial state</button>   
        <div id='Grid'></div>        
    </div>
</body>
</html>

Restore to specific state version

Syncfusion EJ2 TypeScript Grid supports version-based persistence for easy restoration to a specific state. To enable version based persistence, import enableVersionBasedPersistence from @syncfusion/ej2-base and set it globally to true. Define the grid in the template with properties, bind data, and configure persistence using enablePersistence and ej2state-persistenceVersion.

In the below example, the clickHandler method is responsible for handling button clicks corresponding to different versions. Inside this method, the targeted version is assigned to the grid’s ej2state-persistenceVersion dynamically. The code checks if there is already a persisted state for the selected version in the local storage. If found, the grid is updated with the settings retrieved from the local storage, including columns, filter settings, group settings, sort settings, page settings, and selected row index. If no persisted state is found, the current grid state is persisted to the local storage using the getPersistData method.

Here is an example of how to integrate version-based persistence into your EJ2 TypeScript control and restore to specific state version:

import { Grid, Filter, Page, Group, Sort, Reorder} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';
import { enableVersionBasedPersistence } from '@syncfusion/ej2-base';

Grid.Inject(Filter, Page, Group, Sort, Reorder);

enableVersionBasedPersistence(true);

let button1: Button = new Button();
button1.appendTo('#Version1');

let button2: Button  = new Button({ content: 'Version 2' });
button2.appendTo('#Version2');

let button3: Button  = new Button({ content: 'Version 3' });
button3.appendTo('#Version3');

(document.getElementById('Version1')as HTMLElement).addEventListener('click', function () {
    clickHandler('v.1');
});

(document.getElementById('Version2')as HTMLElement).addEventListener('click', function () {
    clickHandler('v.2');
});

(document.getElementById('Version3')as HTMLElement).addEventListener('click', function () {
    clickHandler('v.3');
});

let grid: Grid = new Grid({
  dataSource: data,
  allowPaging: true,
  allowFiltering: true,
  allowSorting: true,
  allowReordering: true,
  allowGrouping: true,
  enablePersistence: true,
  ej2StatePersistenceVersion: 'v.0',
  height: 315,
  columns: [
      { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
      { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
      { field: 'ShipCity', headerText: 'Ship City', width: 150 },
      { field: 'ShipName', headerText: 'Ship Name', width: 150 }
  ],
});
grid.appendTo('#Grid');

function clickHandler(version: string) {
  grid.ej2StatePersistenceVersion = version;
  let persistedGridSettings = window.localStorage.getItem('gridOrderDetails' + grid.ej2StatePersistenceVersion);
  if (persistedGridSettings) {
      grid.setProperties(JSON.parse(persistedGridSettings));
      (document.getElementById('message')as HTMLElement).innerText = 'Grid state restored to ' + version;
  } else {
      let gridData = grid.getPersistData();
      window.localStorage.setItem('gridOrderDetails' + grid.ej2StatePersistenceVersion, gridData);
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        .message {
         text-align: center;
         color: red;
         font-size: 16px;
       }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id="message" class="message"></div>
        <div id="buttons">
            <button id="Version1">Version 1</button>
            <button id="Version2">Version 2</button>
            <button id="Version3">Version 3</button>
        </div>
        <div id="Grid"></div>          
    </div>
</body>
</html>

Restore to previous state

The Syncfusion EJ2 TypeScript Grid control allows you to save and restore its state using local storage. This feature is helpful when you want to preserve the current state of the Grid, such as column order, sorting, and filtering, so that you can return to your previous work or configurations.

To implement this functionality, use the getItem and setItem methods for local storage, along with the Grid control’s setProperties and getPersistData methods.

The provided code demonstrates how to save and restore the previous state of a Syncfusion EJ2 TypeScript Grid control using local storage.

import { Grid, Filter, Page, Group, Sort, Edit, Toolbar} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject(Filter, Page, Group, Sort, Edit, Toolbar);

let saveButton: Button = new Button({ cssClass: 'e-success' });
saveButton.appendTo('#save');

let restoreButton: Button  = new Button({ cssClass: 'e-danger' });
restoreButton.appendTo('#restore');
// Save grid state to local storage
(document.getElementById('save')as HTMLElement).addEventListener('click', function () {
    let persistData = grid.getPersistData(); // Grid persistData
    window.localStorage.setItem("gridOrders", persistData);
    (document.getElementById("message")as HTMLElement).innerText =  "Grid state saved.";
});
// Restore grid state from local storage
(document.getElementById('restore')as HTMLElement).addEventListener('click', function () {
    let value: string = window.localStorage.getItem("gridOrders")as string; //"gridOrders" is control name + control id.
    let state = JSON.parse(value);
    if (state) {
        grid.setProperties(state);
        (document.getElementById("message")as HTMLElement).innerText = "Previous grid state restored.";
    } else {
        (document.getElementById("message")as HTMLElement).innerText = "No saved state found.";
    }
});

let grid: Grid = new Grid({
    dataSource: data,
    allowFiltering: true,
    allowPaging: true,
    pageSettings: { pageCount: 5 },
    allowSorting: true,
    allowGrouping: true,
    groupSettings: { showGroupedColumn: false, columns: ["ShipCountry"] },
    editSettings: { allowEditing: true },
    filterSettings : { type: "Menu" },
    toolbar: ['Edit', 'Update', 'Cancel'],
    enablePersistence: true,
    height: 230,
    columns: [
        { field: 'OrderID', headerText: 'Order ID', width: 140, textAlign: "Right", isPrimaryKey: true, validationRules: { required: true, number: true } },
        { field: 'CustomerID', headerText: 'Customer ID', width: 140, validationRules: { required: true } },
        { field: 'Freight', headerText: 'Freight', width: 140, format: 'C2', textAlign: "Right", editType: "numericedit", validationRules: { required: true } },
        { field: 'OrderDate', headerText: 'OrderDate', width: 120, allowGrouping: false, textAlign: "Right", editType: "datetimepickeredit", format: { type: "dateTime", format: "M/d/y hh:mm a" } },
        { field: 'ShipCountry', headerText: 'Ship Country', width: 150, editType: "dropdownedit", edit: { params: { popupHeight: "300px" } } }
    ],
    actionBegin:()=> {
        (document.getElementById('message')as HTMLElement).innerText  = '';
    },
});
grid.appendTo('#Grid');
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        .message {
         text-align: center;
         color: red;
         font-size: 16px;
       }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id="message" class="message"></div>
        <button id="save">Save</button>
        <button id="restore">Restore</button>
        <div id="Grid"></div>          
    </div>
</body>
</html>

Maintaining custom query in a persistent state

When enablePersistence is enabled, the Grid does not automatically maintain custom query parameters after a page load. This is because the Grid refreshes its query params for every page load. You can maintain the custom query params by resetting the addParams method in the actionBegin event.

import { Grid, Filter, ActionEventArgs, Page } from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';

Grid.Inject(Filter, Page);

let grid: Grid = new Grid({
    dataSource: data,
    allowFiltering: true,
    allowPaging: true,
    enablePersistence: true,
    columns: [
        { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
        { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
        { field: 'EmployeeID', headerText: 'Employee ID', width: 150 },
        { field: 'ShipCity', headerText: 'Ship City', width: 150 },
        { field: 'ShipName', headerText: 'Ship Name', width: 150 }
    ],
    actionBegin: actionBegin,
    height: 230
});
grid.appendTo('#Grid');

function actionBegin(args: ActionEventArgs) {
    grid.query.addParams('dataSource', 'data');
}
<!DOCTYPE html>
<html lang="en">

<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id='Grid'></div>        
    </div>
</body>
</html>

Get or set local storage value

If the enablePersistence property is set to true, the Grid property value is saved in the window.localStorage for reference. You can get or set the localStorage value by using the getItem and setItem methods in window.localStorage.

To retrieve the Grid model from Local Storage, follow these steps:

//get the Grid model.
let value: string = window.localStorage.getItem('gridOrders'); //"gridOrders" is control name + control id.
let model: Object = JSON.parse(value);
//set the Grid model.
window.localStorage.setItem('gridOrders', JSON.stringify(value)); //"gridOrders" is control name + control id.

Prevent columns from persisting

In the Syncfusion EJ2 TypeScript Grid control, you may sometimes want to prevent certain settings from being persisted when using the enablePersistence feature. When the enablePersistence property is set to true, the Grid properties such as Grouping, Paging, Filtering, Sorting, and Columns will persist. You can use the addOnPersist method to prevent these Grid properties from persisting.

The following example demonstrates how to prevent Grid columns from persisting. In the dataBound event of the Grid, you can override the addOnPersist method and remove the columns from the key list given for persistence.

import { Grid, Page, Column} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject(Page);

let grid: Grid = new Grid({
    dataSource: data,
    allowPaging: true,
    enablePersistence: true,
    height: 230,
    columns: [
      { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
      { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
      { field: 'ShipCity', headerText: 'Ship City', width: 150 },
      { field: 'ShipName', headerText: 'Ship Name', width: 150 }
    ],
    dataBound: ()=> {
      let cloned = grid.addOnPersist;
      grid.addOnPersist = function (key: any) {
          key = key.filter((item: string) => item !== "columns");
          return cloned.call(grid, key);
    }},
});
grid.appendTo('#Grid');

let addButton: Button = new Button();
addButton.appendTo('#add');

let removeButton: Button  = new Button();
removeButton.appendTo('#remove');

(document.getElementById('add')as HTMLElement).addEventListener('click', function () {
    let obj = { field: "Freight", headerText: 'Freight', width: 120 };
    (grid.columns as Column[]).push(obj as Column); //you can add the columns by using the Grid columns method
    grid.refreshColumns();
});

(document.getElementById('remove')as HTMLElement).addEventListener('click', function () {
    grid.columns.pop();
    grid.refreshColumns();
});
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <button id="add">Add Columns</button>
        <button id="remove">Remove Columns</button>
        <div id="Grid"></div>          
    </div>
</body>
</html>

Add to persist

Persistence can be added to a Syncfusion EJ2 TypeScript Grid control to enhance the user experience. Persistence allows saving and restoring the state of the grid, including column layouts, sorting, filtering, and other user-specific settings. In this documentation, you will explore how to persist column templates, header templates, and header text settings in the EJ2 TypeScript Grid.

Add a new column in persisted columns list

When the enablePersistence property is set to true in the Syncfusion Grid control, column configurations are persisted. If you need to add new columns to the existing persisted state, you can achieve this by using the Grid’s built-in methods like column.push, and then call the refreshColumns method to update the UI with the new columns.

Here’s an example of how to add a new column to a list of persisted columns:

import { Grid, Page, Column} from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject( Page );

let grid: Grid = new Grid({
    dataSource: data,
    allowPaging: true,
    enablePersistence: true,
    height: 230,
    columns: [
      { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
      { field: 'CustomerID', headerText: 'Customer ID', width: 150 },
      { field: 'ShipCity', headerText: 'Ship City', width: 150 },
      { field: 'ShipName', headerText: 'Ship Name', width: 150 }
    ]
});
grid.appendTo('#Grid');

let addButton: Button = new Button();
addButton.appendTo('#add');

(document.getElementById('add')as HTMLElement).addEventListener('click', function () {
    let obj = { field: "Freight", headerText: 'Freight', width: 120 };
    (grid.columns as Column[]).push(obj as Column); // you can add the columns by using the Grid columns method
    grid.refreshColumns();
});
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <button id="add">Add Columns</button>
        <div id="Grid"></div>          
    </div>
</body>
</html>

  • Adding new columns using Columns directly in the grid initialization is not recommended if you intend to persist the new columns with the existing columns list

Persist the column template, header template and header text

By default, when the enablePersistence property is set to true in the Syncfusion Grid control, certain column properties such as column template, header text, header template, column formatter, and value accessor are not persisted. This is because these properties can be customized at the application level.

To restore these column properties and achieve persistence, you can follow the approach of cloning the grid’s columns property using JavaScript Object’s assign method and manually storing it along with the persist data. When restoring the settings, this cloned column object must be assigned to the grid’s columns property to restore the column settings. The following sample demonstrates this process:

import { Grid, Filter, Page, Column } from '@syncfusion/ej2-grids';
import { data } from './datasource.ts';
import { Button } from '@syncfusion/ej2-buttons';

Grid.Inject(Filter, Page);

let saveButton: Button = new Button();
saveButton.appendTo('#save');

(document.getElementById('save')as HTMLElement).addEventListener('click', function () {
  let persistedGridSettings = JSON.parse(grid.getPersistData());
  let gridColumns =  Object.assign([],(grid.getColumns()));

  persistedGridSettings.columns.forEach(function (persistedColumn: Column ) {
      let column = gridColumns.find(function (col: Column) { return col.field === persistedColumn.field; });
      if (column) {
          persistedColumn.headerText = 'Text Changed';
          persistedColumn.template = (column as Column).template;
          persistedColumn.headerTemplate = (column as Column).headerTemplate;
      }
  });
  window.localStorage.setItem('gridOrders1', JSON.stringify(persistedGridSettings));
  grid.setProperties(persistedGridSettings);
  (document.getElementById('message')as HTMLElement).innerText = 'Saved the headerText, template column, and headerTemplate properties in the persisted settings';
});

let restoreButton: Button  = new Button();
restoreButton.appendTo('#restore');

(document.getElementById('restore')as HTMLElement).addEventListener('click', function () {
    let savedSettings = window.localStorage.getItem('gridOrders1');
  if (savedSettings) {
      grid.setProperties(JSON.parse(savedSettings));
      (document.getElementById('message')as HTMLElement).innerText = 'Restored the headerText, template column, and headerTemplate';
  } else {
      (document.getElementById('message')as HTMLElement).innerText = 'No saved settings found.';
  }
});

let grid: Grid = new Grid({
    dataSource: data,
    allowPaging: true,
    allowFiltering: true,
    enablePersistence: true,
    height: 210,
    columns: [
        { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 },
        { field: 'CustomerID', headerText: 'Customer ID', width: 150, headerTemplate: '<button>HeaderTemplate</button>' },
        { field: 'ShipCity', headerText: 'Ship City', width: 150 },
        { field: 'ShipName', headerText: 'Ship Name', width: 150, template: '#template' }
    ]
});
grid.appendTo('#Grid');
<!DOCTYPE html>
<html lang="en">
<head>
    <title>EJ2 Grid</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Typescript Grid Control" />
    <meta name="author" content="Syncfusion" />
    <link href="index.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-base/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-buttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-popups/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-navigations/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-lists/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-inputs/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-calendars/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet" />
    <link href="https://cdn.syncfusion.com/ej2/27.2.2/ej2-grids/styles/bootstrap5.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        .message {
         text-align: center;
         color: red;
         font-size: 16px;
       }
    </style>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id='loader'>Loading....</div>
    <div id='container'>
        <div id="message" class="message"></div>
        <button id="save">Save column settings</button>
        <button id="restore">Restore column settings</button>
        <div id="Grid"></div>          
    </div>
</body>
</html>