Angular Grid State Persistence
Тhe igxGridState directive allows developers to easily save and restore the grid state. When the IgxGridState directive is applied on the grid, it exposes the getState and setState methods that developers can use to achieve state persistence in any scenario.
Supported Features
IgxGridState directive supports saving and restoring the state of the following features:
SortingFilteringAdvanced FilteringPagingCell SelectionRow SelectionColumn SelectionRow PinningExpansionGroupByColumnsMulti column headers
Multi-row Layout
Columns order
Column properties defined by the
IColumnStateinterface.Columns templates and functions are restored using application level code, see Restoring Column section.
Note
The IgxGridState directive does not take care of templates. Go to Restoring Column section to see how to restore column templates.
Note
The Row Selection feature requires the primaryKey property to be set, so it can be stored/restored correctly.
Usage
getState - This method returns the grid state in a serialized JSON string, so developers can just take it and save it on any data storage (database, cloud, browser localStorage, etc). The method accepts first optional parameter serialize, which determines whether getState will return an IGridState object or a serialized JSON string.
The developer may choose to get only the state for a certain feature/features, by passing in the feature name, or an array with feature names as a second argument.
// get all features` state in a serialized JSON string
const gridState = state.getState();
// get an `IGridState` object, containing all features original state objects, as returned by the grid public API
const gridState: IGridState = state.getState(false);
// get the sorting and filtering expressions
const sortingFilteringStates: IGridState = state.getState(false, ['sorting', 'filtering']);
setState - The setState method accepts the serialized JSON string or IGridState object as argument and will restore the state of each feature found in the object/JSON string.
state.setState(gridState);
state.setState(sortingFilteringStates)
options - The options object implements the IGridStateOptions interface, i.e. for every key, which is the name of a certain feature, there is the boolean value indicating if this feature state will be tracked. getState method will not put the state of these features in the returned value and setState method will not restore state for it.
public options = { cellSelection: false; sorting: false; }
<igx-grid [igxGridState]="options"></igx-grid>
The simple to use single-point API's allows to achieve a full state persistence functionality in just a few lines of code. Copy paste the code from below - it will save the grid state in the browser sessionStorage object every time the user leaves the current page. Whenever the user returns to main page, the grid state will be restored. No more need to configure those complex advanced filtering and sorting expressions every time to get the data you want - do it once and have the code from below do the rest for your users:
// app.component.ts
@ViewChild(IgxGridStateDirective, { static: true })
public state!: IgxGridStateDirective;
public ngOnInit() {
this.router.events.pipe(take(1)).subscribe((event: NavigationStart) => {
this.saveGridState();
});
}
public ngAfterViewInit() {
this.restoreGridState();
}
public saveGridState() {
const state = this.state.getState() as string;
window.sessionStorage.setItem('grid1-state', state);
}
public restoreGridState() {
const state = window.sessionStorage.getItem('grid1-state');
this.state.setState(state);
}
Restoring columns
When possible the state directive will reuses the columns that already exists on the grid when restoring the state, instead of creating new column instances. The only scenario where a new instance will be created is when the column (or its children in case of a column groups) have no field property so there's no way to uniquely identify the matching column and re-use it.
For such scenarios, the following limitations are imposed. In that case restoring complex objects can be achieved with code on application level. Let's show how to do this for templated columns:
- Define a template reference variable (in the example below it is
#activeTemplate) and assign an event handler for thecolumnInitevent:
<igx-grid id="grid" #grid igxGridState (columnInit)="onColumnInit($event)">
<igx-column [field]="'IsActive'" header="IsActive">
<ng-template igxCell #activeTemplate let-column let-val="val">
<igx-checkbox [checked]="val"></igx-checkbox>
</ng-template>
</igx-column>
...
</igx-grid>
- Query the template view in the component using @ViewChild or @ViewChildren decorator. In the
columnInitevent handler, assign the template to the columnbodyTemplateproperty:
@ViewChild('activeTemplate', { static: true }) public activeTemplate: TemplateRef<any>;
public onColumnInit(column: IgxColumnComponent) {
if (column.field === 'IsActive') {
column.bodyTemplate = this.activeTemplate;
column.summaries = MySummary;
column.filters = IgxNumberFilteringOperand.instance();
}
}
Demo
Restoring Strategies
IgxGridState will not persist neither remote operations nor custom dimension strategies (For further information see Grid Remote Operations sample) by default (see limitations). Restoring any of these can be achieved with code on application level. The IgxGridState exposes an event called stateParsed which can be used to additionally modify the grid state before it gets applied. Let's show how to do this:
Note
stateParsed is only emitted when we are using setState with string argument.
- Set custom sorting strategy and custom column and row dimension strategies:
<igx-grid #grid
[data]="data"
[igxGridState]="options"
[sortStrategy]="customStrategy"
[height]="'500px'">
</igx-grid>
@ViewChild(IgxGridStateDirective, { static: true })
public state!: IgxGridStateDirective;
public customStrategy = NoopSortingStrategy.instance();
public options: IGridStateOptions = {...};
- Restoring the state from the
sessionStorageand applying the custom strategies looks like the following:
public restoreState() {
const state = window.sessionStorage.getItem('grid-state');
this.state.stateParsed.pipe(take(1)).subscribe(parsedState => {
parsedState.sorting.forEach(x => x.strategy = NoopSortingStrategy.instance());
});
this.state.setState(state as string);
}
Limitations
getStatemethod uses JSON.stringify() method to convert the original objects to a JSON string. JSON.stringify() does not support Functions, thats why the [IgxGridState] directive will ignore the columnsformatter,filters,summaries,sortStrategy,cellClasses,cellStyles,headerTemplateandbodyTemplateproperties.