Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  41] [ 6]  / answers: 1 / hits: 26798  / 6 Years ago, mon, july 23, 2018, 12:00:00

Using Ag-Grid, users can drag columns to order them the way they like. I need to allow the user to save their column order (to an SQL backend) so that it becomes the default column order for them. I was trying to get the column names like this:



var cols = schedGridOptions.columnApi.getAllColumns();
for (col in cols) {
var colDef = col.getColDef();
console.log(colDef.headerName);
}


This was an example I found for setting the header name, so I tried to adapt it to getting the header name. But I get this error:




JavaScript runtime error: Object doesn't support property or method
'getColDef'




Perhaps I'm not doing this correctly? I'm fairly new at using Ag-Grid. Looking for suggestions.


More From » ag-grid

 Answers
2

You are looking for setColumnState() and getColumnState(). See the docs at https://www.ag-grid.com/javascript-grid-column-api/


In your grid options, set up event handlers for gridReady and columnMoved. https://www.ag-grid.com/javascript-grid-events/


Something like:


gridOptions = {
rowData: myRowDataSource,
columnDefs: myColumns,
onGridReady: onGridReady,
onColumnMoved: onColumnMoved,
}

On the column moved event, save the columnState. Here's an example saved to local storage. Change it to save to your database.


onColumnMoved(params) {
var columnState = JSON.stringify(params.columnApi.getColumnState());
localStorage.setItem('myColumnState', columnState);
}

On the grid ready event, get and restore the grid State. Again, change this to pull from your database.


onGridReady(params) {
var columnState = JSON.parse(localStorage.getItem('myColumnState'));
if (columnState) {
params.columnApi.applyColumnState(columnState, applyOrder:true);
}
}

Updated answer based on comments from @Sebastian and @jsN00b.


[#53904] Thursday, July 19, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
skyler

Total Points: 646
Total Questions: 119
Total Answers: 96

Location: Bonaire
Member since Wed, Mar 29, 2023
1 Year ago
;