State Management in EJ2 JavaScript Grid control

5 Jun 202424 minutes to read

State management in the EJ2 JavaScript 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.

var grid = new ej.grids.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 JavaScript 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.

var gridId = 'OrderDetails';
var grid = new ej.grids.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');

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

document.getElementById('restore').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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id="container">
        <button id="restore"></button>
        <div id="Grid"></div>        
    </div>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</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.

var grid = new ej.grids.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');

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

document.getElementById('restore').onclick = function () {
    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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    
    <div id="container">
        <button id="restore">Restore to initial state</button>   
        <div id="Grid"></div>        
    </div>

<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
      </script>
<script src="index.js" type="text/javascript"></script>
</body></html>

Restore to specific state version

Syncfusion EJ2 JavaScript 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 JavaScript control and restore to specific state version:

ej.base.enableVersionBasedPersistence(true);

var button1 = new ej.buttons.Button({ content: 'Version 1' });
button1.appendTo('#Version1');

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

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

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

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

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

var grid = new ej.grids.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) {
    grid.ej2StatePersistenceVersion = version;
    var persistedGridSettings = window.localStorage.getItem('gridOrderDetails' + grid.ej2StatePersistenceVersion);
    if (persistedGridSettings) {
        grid.setProperties(JSON.parse(persistedGridSettings));
        document.getElementById('message').innerText  = 'Grid state restored to ' + version;
    } else {
        var 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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></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="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>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>

Restore to previous state

The Syncfusion EJ2 JavaScript 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 JavaScript Grid control using local storage.

var grid = new ej.grids.Grid({
    dataSource: data,
    allowFiltering: true,
    allowPaging: true,
    pageSettings: { pageCount: 5 },
    allowSorting: true,
    allowGrouping: true,
    groupSettings: { showGroupedColumn: false, columns: ["ShipCountry"] },
    editSettings: { allowEditing: true },
    toolbar: ['Edit', 'Update', 'Cancel'],
    filterSettings : { type: "Menu" },
    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: function () {
        document.getElementById('message').innerText = '';
    },
  });
  grid.appendTo('#Grid');
  // Save grid state to local storage
  var saveButton = new ej.buttons.Button({cssClass: 'e-success'});
  saveButton.appendTo('#save');
  document.getElementById('save').addEventListener('click', function () {
    var persistData = grid.getPersistData();  // Grid persistData
  window.localStorage.setItem("gridOrders", persistData);
  document.getElementById("message").innerText = "Grid state saved.";
  });
  // Restore grid state from local storage
  var restoreButton = new ej.buttons.Button({cssClass: 'e-danger'});
  restoreButton.appendTo('#restore');
  document.getElementById('restore').addEventListener('click', function () {
    var value = window.localStorage.getItem("gridOrders"); //"gridOrders" is control name + control id.
    var state = JSON.parse(value);
    if (state) {
        grid.setProperties(state);
        document.getElementById("message").innerText = "Previous grid state restored.";
    } else {
        document.getElementById("message").innerText  = "No saved state found.";
    }
  });
<!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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></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="container">
        <div id="message" class="message"></div>
        <button id="save">Save</button>
        <button id="restore">Restore</button>
        <div id="Grid"></div>       
    </div>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</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.

var grid = new ej.grids.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: 270
});
grid.appendTo('#Grid');

function actionBegin() {
    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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id="container">
        <div id="Grid"></div>        
    </div>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</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.
var value = window.localStorage.getItem('gridOrders'); //"gridOrders" is control name + control id.
var model = 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 JavaScript 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.

var grid = new ej.grids.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: function () {
      var cloned = grid.addOnPersist;
      grid.addOnPersist = function (key) {
          key = key.filter((item) => item !== "columns");
          return cloned.call(grid, key);
    }},
  });
  grid.appendTo('#Grid');
  
  var addButton = new ej.buttons.Button();
  addButton.appendTo('#add');
  document.getElementById('add').addEventListener('click', function () {
    var obj = { field: "Freight", headerText: 'Freight', width: 120 };
    grid.columns.push(obj); //you can add the columns by using the Grid columns method
    grid.refreshColumns();
  });
  
  var removeButton = new ej.buttons.Button();
  removeButton.appendTo('#remove');
  document.getElementById('remove').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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id="container">
        <button id="add">Add Columns</button>
        <button id="remove">Remove Columns</button>
        <div id="Grid"></div>       
    </div>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>

Add to persist

Persistence can be added to a Syncfusion EJ2 JavaScript 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 JavaScript 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:

var grid = new ej.grids.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');
  
  var addButton = new ej.buttons.Button();
  addButton.appendTo('#add');
  document.getElementById('add').addEventListener('click', function () {
    var obj = { field: "Freight", headerText: 'Freight', width: 120 };
    grid.columns.push(obj); // 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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></script>
<script src="https://cdn.syncfusion.com/ej2/syncfusion-helper.js" type ="text/javascript"></script>
</head>
<body>
    <div id="container">
        <button id="add">Add Columns</button>
        <div id="Grid"></div>       
    </div>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</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:

var grid = new ej.grids.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');
var saveButton = new ej.buttons.Button();
saveButton.appendTo('#save');

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

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

var restoreButton = new ej.buttons.Button();
restoreButton.appendTo('#restore');
document.getElementById('restore').addEventListener('click', function () {
  var savedSettings = window.localStorage.getItem('gridOrders1');
  if (savedSettings) {
      grid.setProperties(JSON.parse(savedSettings));
      document.getElementById('message').innerText = 'Restored the headerText, template column, and headerTemplate';
  } else {
      document.getElementById('message').innerText = 'No saved settings found.';
  }
});
<!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/26.2.4/ej2-base/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-buttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-popups/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-navigations/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-dropdowns/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-lists/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-inputs/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-calendars/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-splitbuttons/styles/bootstrap5.css" rel="stylesheet">
    <link href="https://cdn.syncfusion.com/ej2/26.2.4/ej2-grids/styles/bootstrap5.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/26.2.4/dist/ej2.min.js" type="text/javascript"></script>
<script src="es5-datasource.js" type="text/javascript"></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="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>
<script>
var ele = document.getElementById('container');
if(ele) {
  ele.style.visibility = "visible";
}   
</script>
<script src="index.js" type="text/javascript"></script>
</body></html>