How do I get and set ag-grid state?
Asked Answered
U

8

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.

Urquhart answered 15/3, 2017 at 13:19 Comment(4)
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?Demonstrate
@Pablo do you have any sample code?Marianamariand
Warning Automatic aggregation when user set grouped will stop working after setColumnStateRamirez
Pls help #65018677Irs
H
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');
}
Highbrow answered 28/8, 2018 at 18:58 Comment(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() }Uveitis
D
12

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

Demonstrate answered 15/3, 2017 at 15:25 Comment(2)
Thank you for the answer. Do you know in which callback I should be restoring the state to the grid?Urquhart
@pupeno for column state restoring, you can use gridOptions.columnApi.setColumnState(colState); in onGridReady() eventTrinitytrinket
G
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

Garcia answered 24/3, 2017 at 11:23 Comment(2)
The problem with the gridReady event is that it fires after the initial grid render. Applying column state on grid ready will first show the default column state, then an animation to the applied column state (i.e. columns size and position changing). This is disturbing for end users.Enucleate
If user refresh page then this solution will not work. plnkr.co/edit/YRH8uQapFU1l37NAjJ9B Its not working if I save and refresh page.Hartal
F
3

As of AG Grid v31, it now has support for loading/saving of grid state via a single combined object. See the AG-1535 feature in their changelog https://ag-grid.com/changelog/.

Reference: https://ag-grid.com/javascript-data-grid/grid-state

Getting the state on any change:

function onStateUpdated(event: StateUpdatedEvent<IOlympicData>): void {
  console.log("State updated", event.state);
}

Getting the state right before the grid is destroyed:

function onGridPreDestroyed(event: GridPreDestroyedEvent<IOlympicData>): void {
  console.log("Grid state on destroy (can be persisted)", event.state);
}

Setting the initial state:

const gridOptions: GridOptions<IOlympicData> = {
  initialState: {}, // <=== Set initial state here
  onGridPreDestroyed: onGridPreDestroyed,
  onStateUpdated: onStateUpdated,
};
Finzer answered 24/3, 2024 at 16:8 Comment(4)
Can you please let me know how to preserve state of the grid if user navigates to different page and comes back to grid page.Hartal
@Hartal Depends on how persistent you want it. Save it to the database and load the state before rendering the grid. Another option is to use the browser localStorage or sessionStorage, which is more ephemeral and tied to the browser, but its faster/easier.Finzer
i am saving it in Local storage but when page refreshes it loads default colsdef.Hartal
@Hartal I cannot troubleshoot your code, but I would start with the most basic scenario. As a test... sort on a column, get the state object, look at the shape of that object, and then hardcode that into the initialState property. Get that working first and then move forward with what you really want.Finzer
C
1

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

Collation answered 20/5, 2019 at 17:11 Comment(0)
E
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;
}
Explicate answered 4/5, 2021 at 3:32 Comment(0)
B
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>
Beaconsfield answered 8/6, 2022 at 16:35 Comment(0)
D
-3

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

Drogue answered 15/3, 2017 at 13:40 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.