---
title: "Grid State"
framework: angular
version: "36.1.0"
---

# Grid State

This section covers saving and restoring the grid state, such as the filter model, selected rows, etc.

## Saving and Restoring State

The following buttons log saving and restoring state to the developer console.

#### Grid State

```ts
import { HttpClient } from "@angular/common/http";
import { Component, signal } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type {
  AutoGroupColumnDef,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridPreDestroyedEvent,
  GridReadyEvent,
  GridState,
  RowSelectionOptions,
  StateUpdatedEvent,
} from "ag-grid-community";
import { ModuleRegistry, enableDevValidations } from "ag-grid-community";
import { AllEnterpriseModule } from "ag-grid-enterprise";

import type { IOlympicData } from "./interfaces";
import "./styles.css";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllEnterpriseModule]);

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="example-wrapper">
      <div>
        <span class="button-group">
          <button (click)="reloadGrid()">
            Recreate Grid with Current State
          </button>
          <button (click)="printState()">Print State</button>
        </span>
      </div>
      @if (gridVisible()) {
        <ag-grid-angular
          style="width: 100%; height: 100%;"
          gridId="gridState"
          [columnDefs]="columnDefs"
          [defaultColDef]="defaultColDef"
          [defaultColGroupDef]="defaultColGroupDef"
          [autoGroupColumnDef]="autoGroupColumnDef"
          [sideBar]="true"
          [pagination]="true"
          [rowSelection]="rowSelection"
          [cellSelection]="true"
          [calculatedColumns]="true"
          [enableRowPinning]="true"
          [suppressColumnMoveAnimation]="true"
          [ensureDomOrder]="true"
          [rowData]="rowData"
          [initialState]="initialState"
          [gridOptions]="gridOptions"
          (stateUpdated)="onStateUpdated($event)"
          (gridReady)="onGridReady($event)"
        />
      }
    </div>
  `,
})
export class AppComponent {
  private gridApi!: GridApi<IOlympicData>;

  public columnDefs: (ColDef | ColGroupDef)[] = [
    { field: "athlete", minWidth: 150 },
    { field: "age" },
    { field: "country", minWidth: 150 },
    {
      headerName: "Competition",
      groupId: "competition",
      children: [
        { field: "year" },
        { field: "date", minWidth: 150 },
        { field: "sport", minWidth: 150 },
      ],
    },
    {
      headerName: "Medals",
      groupId: "medals",
      children: [
        { field: "gold" },
        { field: "silver", columnGroupShow: "open" },
        { field: "bronze", columnGroupShow: "open" },
        { field: "total", columnGroupShow: "closed" },
      ],
    },
  ];
  public defaultColDef: ColDef = {
    flex: 1,
    minWidth: 100,
    filter: true,
    enableRowGroup: true,
    enablePivot: true,
    enableValue: true,
    headerNameEditable: true,
  };
  public defaultColGroupDef: Partial<ColGroupDef> = {
    headerNameEditable: true,
  };
  public autoGroupColumnDef: AutoGroupColumnDef = { minWidth: 200 };
  public rowSelection: RowSelectionOptions = {
    mode: "multiRow",
  };
  public rowData?: IOlympicData[];
  public gridVisible = signal(true);
  public initialState?: GridState;
  public gridOptions: GridOptions = {
    onGridPreDestroyed: (params: GridPreDestroyedEvent<IOlympicData>) => {
      console.log("Grid state on destroy (can be persisted)", params.state);
    },
  };

  constructor(private http: HttpClient) {}

  reloadGrid(): void {
    const state = this.gridApi.getState();
    this.gridVisible.set(false);
    this.initialState = state;
    this.rowData = undefined;
    setTimeout(() => {
      this.gridVisible.set(true);
    });
  }

  printState(): void {
    console.log("Grid state", this.gridApi.getState());
  }

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

  onGridReady(params: GridReadyEvent<IOlympicData>): void {
    this.gridApi = params.api;
    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Grid State](https://www.ag-grid.com/examples/grid-state/grid-state/angular)

The initial state is provided via the grid option `initialState`. It is only read once when the grid is created.

```ts
<ag-grid-angular
    [initialState]="initialState"
    /* other grid options ... */ />

this.initialState = {
    filter: {
        filterModel: {
            year: {
                filterType: 'set',
                values: ['2012'],
            }
        }
    },
    columnVisibility: {
        hiddenColIds: ['athlete'],
    },
    rowGroup: {
        groupColIds: ['athlete'],
    }
};
```

The current grid state can be retrieved by listening to the state updated event, which is fired with the latest state when it changes, or via `api.getState()`.

The state is also passed in the [Grid Pre-Destroyed Event](https://www.ag-grid.com/angular-data-grid/grid-lifecycle/#grid-pre-destroyed), which can be used to get the state when the grid is destroyed.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `gridPreDestroyed` | `GridPreDestroyedEvent` |  |  | Invoked immediately before the grid is destroyed. This is useful for cleanup logic that needs to run before the grid is torn down. |
| `stateUpdated` | `StateUpdatedEvent` |  |  | Grid state has been updated. |

## State Contents

The following is captured in the grid state:

- [Aggregation Functions](https://www.ag-grid.com/angular-data-grid/aggregation/) (column state)
- [Opened Column Groups](https://www.ag-grid.com/angular-data-grid/column-groups/)
- [Column Order](https://www.ag-grid.com/angular-data-grid/column-moving/) (column state)
- [Pinned Columns](https://www.ag-grid.com/angular-data-grid/column-pinning/) (column state)
- [Column Sizes](https://www.ag-grid.com/angular-data-grid/column-sizing/) (column state)
- [Hidden Columns](https://www.ag-grid.com/angular-data-grid/column-properties/#reference-display-hide) (column state)
- [Column Filter Model](https://www.ag-grid.com/angular-data-grid/filtering/)
- [Advanced Filter Model](https://www.ag-grid.com/angular-data-grid/filter-advanced/#filter-model--api)
- [Focused Cell](https://www.ag-grid.com/angular-data-grid/keyboard-navigation/) ([Client-Side Row Model](https://www.ag-grid.com/angular-data-grid/row-models/) only)
- [Current Page](https://www.ag-grid.com/angular-data-grid/row-pagination/)
- [Pivot Mode and Columns](https://www.ag-grid.com/angular-data-grid/pivoting/) (column state)
- [Cell Selection](https://www.ag-grid.com/angular-data-grid/cell-selection/)
- [Row Group Columns](https://www.ag-grid.com/angular-data-grid/grouping/) (column state)
- [Expanded Row Groups](https://www.ag-grid.com/angular-data-grid/grouping-opening-groups/)
- [Row Selection](https://www.ag-grid.com/angular-data-grid/row-selection/) (retrievable for all row models, but can only be set for [Client-Side Row Model](https://www.ag-grid.com/angular-data-grid/row-models/) and [Server-Side Row Model](https://www.ag-grid.com/angular-data-grid/row-models/))
- [Pinned Rows](https://www.ag-grid.com/angular-data-grid/row-pinning/)
- [Show Values As](https://www.ag-grid.com/angular-data-grid/aggregation-show-values-as/) (column state)
- [Side Bar](https://www.ag-grid.com/angular-data-grid/side-bar/)
- [Sort](https://www.ag-grid.com/angular-data-grid/row-sorting/) (column state)
- [Calculated Columns](https://www.ag-grid.com/angular-data-grid/calculated-columns/) added or modified by end users

> **Note**
>
> When restoring the current page using the [Server Side Row Model](https://www.ag-grid.com/angular-data-grid/server-side-model/) or [Infinite Row Model](https://www.ag-grid.com/angular-data-grid/infinite-scrolling/), additional configuration is required:
>
> - For the Server Side Row Model - set the `serverSideInitialRowCount` property to a value which includes the rows to be shown.
> - For the Infinite Row Model - set the `infiniteInitialRowCount` property to a value which includes the rows to be shown.

All state properties are optional, so a property can be excluded if you do not want to restore it.

If applying some but not all of the column state properties, then `initialState.partialColumnState` must be set to `true`.

`partialColumnState` controls *which* column state sections you supply, not whether those sections may themselves be partial. Any section you include must match its documented shape.

The state also contains the grid version number. When applying state with older version numbers, any old state properties will be automatically migrated to the current format.

The grid state is designed to be serialisable, so any functions will be stripped out. For example, aggregation functions should be [Registered as Custom Functions](https://www.ag-grid.com/angular-data-grid/aggregation-custom-functions/#registering-custom-functions) to work with state rather than being set as [Directly Applied Functions](https://www.ag-grid.com/angular-data-grid/aggregation-custom-functions/#directly-applied-functions).

Properties available on the `GridState` interface.

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `version` | `string` |  |  | Grid version number |
| `aggregation` | `AggregationState` |  |  | Includes aggregation functions (column state) |
| `columnGroup` | `ColumnGroupState` |  |  | Includes opened groups |
| `columnOrder` | `ColumnOrderState` |  |  | Includes column ordering (column state) |
| `columnPinning` | `ColumnPinningState` |  |  | Includes left/right pinned columns (column state) |
| `columnSizing` | `ColumnSizingState` |  |  | Includes column width/flex (column state) |
| `columnVisibility` | `ColumnVisibilityState` |  |  | Includes hidden columns (column state) |
| `columnHeaderName` | `ColumnHeaderNameState` |  |  | Includes user-edited column header names (column state) |
| `filter` | `FilterState` |  |  | Includes Column Filters and Advanced Filter |
| `focusedCell` | `FocusedCellState` |  |  | Includes currently focused cell. Works for Client-Side Row Model only |
| `pagination` | `PaginationState` |  |  | Includes current page |
| `rowPinning` | `RowPinningState` |  |  | Includes currently manually pinned rows |
| `pivot` | `PivotState` |  |  | Includes current pivot mode and pivot columns (column state) |
| `cellSelection` | `CellSelectionState` |  |  | Includes currently selected cell ranges |
| `rowGroup` | `RowGroupState` |  |  | Includes current row group columns (column state) |
| `rowGroupExpansion` | `RowGroupExpansionState` |  |  | Includes currently expanded group rows |
| `ssrmRowGroupExpansion` | `RowGroupExpansionState \| RowGroupBulkExpansionState` |  |  | Includes currently expanded group rows when using ssrmExpandAllAffectsAllRows |
| `rowSelection` | `string[] \| ServerSideRowSelectionState \| ServerSideRowGroupSelectionState` |  |  | Includes currently selected rows. For Server-Side Row Model, will be `ServerSideRowSelectionState \| ServerSideRowGroupSelectionState`, for other row models, will be an array of row IDs. Can only be set for Client-Side Row Model and Server-Side Row Model. |
| `scroll` | `ScrollState` |  |  | Includes current scroll position. Works for Client-Side Row Model only |
| `sideBar` | `SideBarState` |  |  | Includes current Side Bar positioning and opened tool panel |
| `sort` | `SortState` |  |  | Includes current sort columns and direction (column state) |
| `showValuesAs` | `ShowValuesAsState` |  |  | Includes the per-column "Show Values As" mode (column state) |
| `userColumns` | `UserColumnState[]` |  |  | Includes columns the user created at runtime (e.g. via the Calculated Column dialog), and the properties the user changed on or removals of columns declared in `columnDefs`. Unlike the other sections, which configure existing columns, this section can create and remove them. |
| `partialColumnState` | `boolean` |  |  | When providing a partial `initialState` with some but not all column state properties, set this to `true`. This controls which top-level sections are supplied, not whether a section may itself be partial: any section you provide must match its documented shape. Not required if passing the whole state object retrieved from the grid. Not used for `api.setState()`, as that instead takes a second argument of properties to ignore. |

## Column and Group IDs

> **Warning**
>
> Give every column a `colId` or a `field`, and every column group a `groupId`. Without them, state can be restored onto the wrong column.

Columns are identified in the state by their [Column ID](https://www.ag-grid.com/angular-data-grid/column-updating-definitions/#matching-columns), and [Column Groups](https://www.ag-grid.com/angular-data-grid/column-groups/) by their `groupId`. These IDs are the only link between a saved state and the columns it describes, so they need to mean the same thing when the state is restored as they did when it was saved.

A column that provides neither `colId` nor `field` - one using only a `valueGetter`, for example - is given a positional ID instead. That ID follows the column's position in `columnDefs` rather than the column itself. If the definitions are reordered between saving and restoring, each column's state is applied to whichever column now occupies its old position.

This affects every column state section: sizes, sort, pinning, visibility, order and header names. A restored grid can silently show another column's width, or a header the user renamed on the wrong column.

Column groups behave the same way. A group definition without a `groupId` is given a generated ID which changes when the column definitions change, so the open / closed state of that group may not be restored.

## Setting State

The best way to restore grid state is via initial state as described above. However, it is also possible to restore state on an existing grid via `api.setState(state)`.

> **Note**
>
> `setState` should only be used to restore grid state. The grid does not support being used as a controlled component, so do not call this on every state update.

#### Setting State

```ts
import { HttpClient } from "@angular/common/http";
import { Component, signal } from "@angular/core";

import { AgGridAngular } from "ag-grid-angular";
import type {
  AutoGroupColumnDef,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  GridPreDestroyedEvent,
  GridReadyEvent,
  GridState,
  RowSelectionOptions,
  StateUpdatedEvent,
} from "ag-grid-community";
import { ModuleRegistry, enableDevValidations } from "ag-grid-community";
import { AllEnterpriseModule } from "ag-grid-enterprise";

import type { IOlympicData } from "./interfaces";
import "./styles.css";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([AllEnterpriseModule]);

@Component({
  standalone: true,
  imports: [AgGridAngular],
  selector: "my-app",
  template: `
    <div class="example-wrapper">
      <div>
        <span class="button-group">
          <button (click)="saveState()">Save State</button>
          <button (click)="reloadGrid()">Recreate Grid with No State</button>
          <button (click)="setState()">Set State</button>
          <button (click)="printState()">Print State</button>
        </span>
      </div>
      @if (gridVisible()) {
        <ag-grid-angular
          style="width: 100%; height: 100%;"
          gridId="setState"
          [columnDefs]="columnDefs"
          [defaultColDef]="defaultColDef"
          [defaultColGroupDef]="defaultColGroupDef"
          [autoGroupColumnDef]="autoGroupColumnDef"
          [sideBar]="true"
          [pagination]="true"
          [rowSelection]="rowSelection"
          [cellSelection]="true"
          [calculatedColumns]="true"
          [enableRowPinning]="true"
          [suppressColumnMoveAnimation]="true"
          [rowData]="rowData"
          [gridOptions]="gridOptions"
          (stateUpdated)="onStateUpdated($event)"
          (gridReady)="onGridReady($event)"
        />
      }
    </div>
  `,
})
export class AppComponent {
  private gridApi!: GridApi<IOlympicData>;

  public columnDefs: (ColDef | ColGroupDef)[] = [
    { field: "athlete", minWidth: 150 },
    { field: "age" },
    { field: "country", minWidth: 150 },
    {
      headerName: "Competition",
      groupId: "competition",
      children: [
        { field: "year" },
        { field: "date", minWidth: 150 },
        { field: "sport", minWidth: 150 },
      ],
    },
    {
      headerName: "Medals",
      groupId: "medals",
      children: [
        { field: "gold" },
        { field: "silver", columnGroupShow: "open" },
        { field: "bronze", columnGroupShow: "open" },
        { field: "total", columnGroupShow: "closed" },
      ],
    },
  ];
  public defaultColDef: ColDef = {
    flex: 1,
    minWidth: 100,
    filter: true,
    enableRowGroup: true,
    enablePivot: true,
    enableValue: true,
    headerNameEditable: true,
  };
  public defaultColGroupDef: Partial<ColGroupDef> = {
    headerNameEditable: true,
  };
  public autoGroupColumnDef: AutoGroupColumnDef = { minWidth: 200 };
  public rowSelection: RowSelectionOptions = {
    mode: "multiRow",
  };
  public rowData?: IOlympicData[];
  public gridVisible = signal(true);
  public gridOptions: GridOptions = {
    onGridPreDestroyed: (params: GridPreDestroyedEvent<IOlympicData>) => {
      console.log("Grid state on destroy (can be persisted)", params.state);
    },
  };

  private savedState?: GridState;

  constructor(private http: HttpClient) {}

  reloadGrid(): void {
    this.gridVisible.set(false);
    this.rowData = undefined;
    setTimeout(() => {
      this.gridVisible.set(true);
    });
  }

  printState(): void {
    console.log("Grid state", this.gridApi.getState());
  }

  saveState(): void {
    this.savedState = this.gridApi.getState();
    console.log("Saved state", this.savedState);
  }

  setState(): void {
    if (this.savedState) {
      this.gridApi.setState(this.savedState);
      console.log("Set state", this.savedState);
    }
  }

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

  onGridReady(params: GridReadyEvent<IOlympicData>): void {
    this.gridApi = params.api;
    this.http
      .get<
        IOlympicData[]
      >("https://www.ag-grid.com/example-assets/olympic-winners.json")
      .subscribe((data) => (this.rowData = data));
  }
}
```

[Live example: Setting State](https://www.ag-grid.com/examples/grid-state/set-state/angular)

It is possible to maintain the existing state for individual state contents by passing a second argument to `setState` that contains the top-level properties to ignore. E.g. `api.setState(state, ['filter'])` will maintain the existing filter state in the grid.

## Converting Column State to Grid State

State retrieved via the [Column State](https://www.ag-grid.com/angular-data-grid/column-state/) APIs can be converted into grid state via the helper functions `convertColumnState` and `convertColumnGroupState`.

```
const state = {
    ...convertColumnState(columnState),
    ...convertColumnGroupState(columnGroupState)
};
```
