angularag-gridag-grid-angular

How can I restore the selected row state in Ag grid


I would like to fully restore the state of the grid before the user navigated away. That includes the selected(highlighted) row the user clicked on.

I am programatically storing the state of ag grid when a user navigates away from the grid during the row on click event:

  override onGridRowClicked(event: RowClickedEvent<any, any>): void {
    const id = event.data._id;

    this.service.gridState = event.api.getState();
    console.log(this.service.gridState);

    this.router.navigate([id], { relativeTo: this.route });
  }

a quick console log does reveal that the selected row's id is selected

{
    "version": "32.1.0",
    ...
    "rowSelection": [
        "id"
    ],
    ...
}

and when the grids initial state is set when the user returns to the grid in the constructor:

  constructor(
  ) {
    super(route, router);
    this.gridOptions.initialState = this.service.gridState;
  }

the sortmodel is restored, but not the selected row.


Solution

  • Ag-Grid has a great example on their website for storing and restoring state.

    The example has the sort and selection restored.

    Use onGridPreDestroyed to store the state in a service.

    public gridOptions: GridOptions = {
        onGridPreDestroyed: (params: GridPreDestroyedEvent<IOlympicData>) => {
            console.log('Grid state on destroy (can be persisted)', params.state);
        },
    };
    

    Then use the initialState property binding to restore the state.

                <ag-grid-angular
                    ...
                    [initialState]="initialState"
                    ...
                />
    

    Ag Grid Docs - Saving and Restoring State

    Plunkr Demo