Pablo Fernandez
Pablo Fernandez

Reputation: 287440

How do I get and set ag-grid state?

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.

Upvotes: 27

Views: 47278

Answers (8)

Casey Plummer
Casey Plummer

Reputation: 3068

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,
};

Upvotes: 4

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

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>

Upvotes: 0

Aaron Hudon
Aaron Hudon

Reputation: 5839

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;
}

Upvotes: 1

Sean Landsman
Sean Landsman

Reputation: 7179

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

Upvotes: 7

Hamid
Hamid

Reputation: 478

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');
}

Upvotes: 20

aswininayak
aswininayak

Reputation: 973

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

Upvotes: 1

Jarod Moser
Jarod Moser

Reputation: 7338

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

Upvotes: 12

zapping
zapping

Reputation: 4116

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

Upvotes: -3

Related Questions