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.
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.setColumnState(columnState);
}
}