Category / Section
How to maintain expand/collapsed state of rows during page refresh in Javascript TreeGrid?
3 mins read
This article explains how to maintain the expand/collapse state of rows during a page refresh in Javascript Treegrid
You can maintain expand/collapse state of rows during a page refresh using the dataBound event.
- You can save the collapsed records to localStorage in collapsed event of Tree Grid by using the setItem method.
- On page refresh, dataBound event will be triggered. In that event, retrieve the saved records by using the getItem method and collapse the specific rows by using the collapseRow method of the Tree Grid by passing the row details.
Index.js
var currentData = [] var treeGridObj = new ej.treegrid.TreeGrid({ dataSource: sampleData, childMapping: 'subtasks', height: 350, treeColumnIndex: 1, allowPaging: true, dataBound: dataBound, collapsed: collapsed, expanded: expanded, columns: [ { field: 'taskID', isPrimaryKey: true, headerText: 'Task ID', width: 70, textAlign: 'Right', }, { field: 'taskName', headerText: 'Task Name', width: 200, textAlign: 'Left', }, { field: 'startDate', headerText: 'Start Date', width: 90, textAlign: 'Right', type: 'date', format: 'yMd', }, { field: 'endDate', headerText: 'End Date', width: 90, textAlign: 'Right', type: 'date', format: 'yMd', }, { field: 'duration', headerText: 'Duration', width: 80, textAlign: 'Right', }, { field: 'progress', headerText: 'Progress', width: 80, textAlign: 'Right', }, { field: 'priority', headerText: 'Priority', width: 90 }, ], }); treeGridObj.appendTo('#TreeGrid'); function collapsed(args) { currentData.push(args.data); store(args); //storing collapsed record in local storage using setItem method } function expanded(args) { currentData.push(args.data); this.store(args); //storing collapsed record in local storage using setItem method } function store(args) { currentData.push(...treeGridObj.getCurrentViewRecords(). filter((i) => i.hasChildRecords).filter((i) => !i.expanded)); this.currentData = Array.from(new Set(this.currentData)); window.localStorage.setItem('currentData', JSON.stringify(currentData)); } function dataBound(args) { if (treeGridObj.initialRender) { //checking whether it is initial rendering var data = JSON.parse(window.localStorage.getItem('currentData')); //retriving collapsed record in local storage using getItem method if (data) { var completeData = treeGridObj.grid.dataSource; var primaryKeyFieldName = treeGridObj.getPrimaryKeyFieldNames()[0]; for (var i = 0; i < data.length; i++) { var value = []; for (var j = 0; j < completeData.length; j++) { if (completeData[j][primaryKeyFieldName] == data[i][primaryKeyFieldName]) { value = completeData[j]; } } treeGridObj.collapseRow(null, value); //collapsing row using collapseRow } currentData = []; window.localStorage.setItem('currentData', JSON.stringify(currentData)); } } }
Refer to the working sample for additional details and implementation: View Sample in Stackblitz