27

How can I obtain and re-set the state of an ag-grid table? I mean, which columns are being show, in what order, with what sorting and filtering, etc.

Update: getColumnState and setColumnState seem to be close to what I want, but I cannot figure out the callbacks in which I should save and restore the state. I tried restoring it in onGridReady but when the actual rows are loaded, I lose the state.

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • I'm not sure I understand the flow of your application, I think we'll need that in order to answer where you should 'restore the state'. What is happening between saving a state and restoring a state? – Jarod Moser Mar 23 '17 at 23:06
  • @Pablo do you have any sample code? – Sagar V Mar 27 '17 at 14:44
  • 2
    **Warning** Automatic aggregation when user set grouped will stop working after setColumnState – Nikita Fedorov May 09 '19 at 19:11
  • Pls help https://stackoverflow.com/questions/65018177/ag-grid-community-infinite-row-model-for-server-side-pagination-community-free/65040658#65040658 – NeverGiveUp161 Dec 03 '20 at 06:16

7 Answers7

20

There is a very specific example on their website providing details for what you are trying to do: javascript-grid-column-definitions

function saveState() {
    window.colState = gridOptions.columnApi.getColumnState();
    window.groupState = gridOptions.columnApi.getColumnGroupState();
    window.sortState = gridOptions.api.getSortModel();
    window.filterState = gridOptions.api.getFilterModel();
    console.log('column state saved');
}

and for restoring:

function restoreState() {
    gridOptions.columnApi.setColumnState(window.colState);
    gridOptions.columnApi.setColumnGroupState(window.groupState);
    gridOptions.api.setSortModel(window.sortState);
    gridOptions.api.setFilterModel(window.filterState);
    console.log('column state restored');
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Hamid
  • 479
  • 6
  • 21
  • 1
    If you want to save state whenever something changes, you can add event handlers to your grid options like this: onSortChanged: () => { saveState() }, onFilterChanged: () => { saveState() }, onColumnResized: () => { saveState() }, onColumnMoved: () => { saveState() } – John Gilmer Sep 17 '20 at 13:02
11

I believe you are looking for this page of the Docs. This describes the column api and what functions are available to you. The functions that are of most relevance would be:

  • getAllDisplayedColumns() - used to show what columns are able to be rendered into the display. Due to virtualization there may be some columns that aren't rendered to the DOM quite yet, iff you want only the columns rendered to the DOM then use getAllDisplayedVirtualColumns() - both functions show the order as they will be displayed on the webpage
    • The Column object that is returned from these functions contains sort and filter attributes for each of the columns.

I believe that all you need would be available to you from that function which would be called like this gridOptions.columnApi.getAllDisplayedColumns()

Other functions which might be useful:

  • Available from gridOptions.columnApi:
    • getColumnState() - returns objects with less detail than the above funciton - only has: aggFunc, colId, hide, pinned, pivotIndex, rowGroupIndex and width
    • setColumnState(columnState) - this allows you to set columns to hidden, visible or pinned, columnState should be what is returned from getColumnState()
  • Available from gridOptions.api:
    • getSortModel() - gets the current sort model
    • setSortModel(model) - set the sort model of the grid, model should be the same format as is returned from getSortModel()
    • getFilterModel() - gets the current filter model
    • setFilterModel(model) - set the filter model of the grid, model should be the same format as is returned from getFilterModel()

There are other functions that are more specific, if you only want to mess with pinning a column you can use setColumnPinned or for multiple columns at once use setColumnsPinned and more functions are available from the linked pages of the AG-Grid docs

Jarod Moser
  • 7,022
  • 2
  • 24
  • 52
7

The gridReady event should do what you need it to do. What I suspect is happening is your filter state is being reset when you update the grid with data - you can alter this behaviour by setting filterParams: {newRowsAction: 'keep'}

This can either by set by column, or set globally with defaultColDef.

Here is a sample configuration that should work for you:

var gridOptions = {
    columnDefs: columnDefs,
    enableSorting: true,
    enableFilter: true,
    onGridReady: function () {
        gridOptions.api.setFilterModel(filterState);
        gridOptions.columnApi.setColumnState(colState);
        gridOptions.api.setSortModel(sortState);
    },
    defaultColDef: {
        filterParams: {newRowsAction: 'keep'}
    }
};

I've created a plunker here that illustrates how this would work (note I'm restoring state from hard code strings, but the same principle applies): https://plnkr.co/edit/YRH8uQapFU1l37NAjJ9B . The rowData is set on a timeout 1 second after loading

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Sean Landsman
  • 7,033
  • 2
  • 29
  • 33
1

To keep the filter values you may use filterParams: {newRowsAction: 'keep'}

aswininayak
  • 933
  • 5
  • 22
  • 39
1

Here's my approach. It simply involves creating a wrapper function with the same API as instantiating the agGrid.

A few things of interest in this function

  • saves/loads to local storage
  • makes use of the addEventListener that becomes available to the options object once it is passed in to the Grid function.
  • attaches to the onGridReady callback of the options object without erasing what may already be defined.

usage:

newAgGrid(document.getElementById('my-grid'), options);
    
static newAgGrid(element, options) {
    const ls = window.localStorage;
    const key = `${location.pathname}/${element.id}`;
    const colStateKey = `${key}colstate`;
    const sortStateKey = `${key}sortState`;
    function saveState(params) {
        if (ls) {
            ls.setItem(colStateKey, JSON.stringify(params.columnApi.getColumnState()));
            ls.setItem(sortStateKey, JSON.stringify(params.api.getSortModel()));
        }
    }
    function restoreState(params) {
        if (ls) {
            const colState = ls.getItem(colStateKey);
            if (colState) {
                params.columnApi.setColumnState(JSON.parse(colState));
            }
            const sortState = ls.getItem(sortStateKey)
            if (sortState) {
                params.api.setSortModel(JSON.parse(sortState));
            }
        }
    }
    // monitor the onGridReady event.  do not blow away an existing handler
    let existingGridReady = undefined;
    if (options.onGridReady) {
        existingGridReady = options.onGridReady;
    }
    options.onGridReady = function (params) {
        if (existingGridReady) {
            existingGridReady(params);
        }
        restoreState(params);
    }
    // construct grid
    const grid = new agGrid.Grid(element, options);
    // now that grid is created, add in additional event listeners
    options.api.addEventListener("sortChanged", function (params) {
        saveState(params);
    });
    options.api.addEventListener("columnResized", function (params) {
        saveState(params);
    });
    options.api.addEventListener("columnMoved", function (params) {
        saveState(params);
    });
    return grid;
}
Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60
0

we can use useRef() to refer <AgGridReact> element to access getColumn and setColumn state in following way.

const GridRef = useRef()

GridRef.current.columnApi.getColumnState() //  get Column state value
GridRef.current.columnApi.setColumnState() //  set Column state value

<AgGridReact
   enableFilter={true}
   rowStyle={rowStyle}
   ref={GridRef}
></AgGridReact>
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
-2

The following needs to be done.

Include a div for the grid in your html

<div id="myGrid" style="width: 500px; height: 200px;"></div>

On the js side

//initialize your grid object
var gridDiv = document.querySelector('#myGrid');



//Define the columns options and the data that needs to be shown
        var gridOptions = {
            columnDefs: [
                {headerName: 'Name', field: 'name'},
                {headerName: 'Role', field: 'role'}
            ],
            rowData: [
                {name: 'Niall', role: 'Developer'},
                {name: 'Eamon', role: 'Manager'},
                {name: 'Brian', role: 'Musician'},
                {name: 'Kevin', role: 'Manager'}
            ]
        };

//Set these up with your grid
        new agGrid.Grid(gridDiv, gridOptions);

Check this pen out for more features. https://codepen.io/mrtony/pen/PPyNaB . Its done with angular

zapping
  • 4,118
  • 6
  • 38
  • 56