Web Components Persistencia del estado de la cuadrícula pivotante
The Ignite UI for Web Components State Persistence in Web Components Pivot Grid allows developers to easily save and restore the grid state. When the IgcGridStateComponent is applied on the Web Components IgcPivotGridComponent, it exposes the getState, getStateAsString, applyState and applyStateFromString methods that developers can use to achieve state persistence in any scenario.
Supported Features
IgcGridStateComponentSoporta guardar y restaurar el estado de las siguientes características:
SortingFilteringCellSelectionColumnSelectionExpansionIgcPivotConfiguration- Pivot Configuration properties defined by the
IPivotConfigurationinterface. - Las funciones de Dimensión y Valor de Pivot se restauran utilizando código de nivel de aplicación; consulte la sección Restauración de la configuración de Pivot.
- Las estrategias de fila y columna dinámicas también se restauran utilizando código a nivel de aplicación; consulte la sección Restauración de estrategias dinámicas.
- Pivot Configuration properties defined by the
Usage
ElgetState método devuelve el estado de la cuadrícula en unIgcGridStateInfo objeto, que contiene toda la información del estado. Puede que se requieran pasos adicionales para salvarlo.
DevuelvegetStateAsString una cadena JSON serializada, así que los desarrolladores pueden simplemente usarla y guardarla en cualquier almacenamiento de datos (base de datos, nube, navegador localStorage, etc.).
El desarrollador puede optar por obtener solo el estado de una determinada característica o características, pasando una matriz con nombres de características como argumento. La matriz vacía dará como resultado el uso de las opciones de estado predeterminadas.
<igc-pivot-grid id="grid">
<igc-grid-state id="gridState"></igc-grid-state>
</igc-pivot-grid>
var gridState = document.getElementById('gridState') as IgcGridStateComponent;
// get an `IgcGridStateInfo` object, containing all features original state objects, as returned by the grid public API
const state: IgcGridStateInfo = gridState.getState();
// get all features` state in a serialized JSON string
const stateString: string = gridState.getStateAsString();
// get the sorting and filtering expressions
const sortingFilteringStates: IgcGridStateInfo = gridState.getState(['sorting', 'filtering']);
applyState- El método acepta unIgcGridStateInfo objeto como argumento y restaurará el estado de cada característica encontrada en el objeto o características especificadas como segundo argumento.
applyStateFromString- El método acepta una cadena JSON serializada como argumento y restaurará el estado de cada característica encontrada en la cadena JSON o características especificadas como segundo argumento.
gridState.applyState(gridState);
gridState.applyStateFromString(gridStateString);
gridState.applyState(sortingFilteringStates)
Eloptions objeto implementa laIgcGridStateOptions interfaz, es decir, para cada clave, que es el nombre de una determinada característica, existe el valor booleano que indica si este estado de la característica será rastreado.getState /getStateAsString methods no pondrá el estado de estas características en el valor devuelto yapplyState /applyStateFromString methods no restaurará el estado para ellas.
gridState.options = { cellSelection: false, sorting: false };
Las APIs de punto único, sencillas de usar, permiten lograr una funcionalidad de persistencia completa de estado en solo unas pocas líneas de código. Copia y pega el código de abajo: guardará el estado de la cuadrícula en el objeto del navegadorLocalStorage cada vez que el usuario salga de la página actual. Cada vez que el usuario regresa a la página principal, el estado de la cuadrícula se restaurará. Ya no hace falta configurar esos complejos filtrados avanzados y ordenar expresiones cada vez para obtener los datos que quieres: hazlo una vez y el código de abajo hace el resto por tus usuarios:
constructor() {
window.addEventListener("load", () => { this.restoreGridState(); });
window.addEventListener("beforeunload", () => { this.saveGridState(); });
}
// Using methods that work with IgcGridStateInfo object.
public saveGridState() {
const state = this.gridState.getState();
window.localStorage.setItem('grid-state', JSON.stringify(state));
}
public restoreGridState() {
const state = window.localStorage.getItem('grid-state');
if (state) {
this.gridState.applyState(JSON.parse(state));
}
}
// Or using string alternative methods.
public saveGridStateString() {
const state = this.gridState.getStateAsString();
window.localStorage.setItem('grid-state', state);
}
public restoreGridStateString() {
const state = window.localStorage.getItem('grid-state');
if (state) {
this.gridState.applyStateFromString(state);
}
}
Restoring Pivot Configuration
IgcGridStateComponent will not persist pivot dimension functions, value formatters, etc. by default (see limitations). Restoring any of these can be achieved with code on application level. The IgcPivotGridComponent exposes two events which can be used to set back any custom functions you have in the configuration: DimensionInit and ValueInit. Let's show how to do this:
- Assign event handlers for the
DimensionInitandValueInitevents:
constructor() {
var grid = document.getElementById('grid') as IgcPivotGridComponent;
grid.pivotConfiguration = this.pivotConfiguration;
grid.addEventListener("valueInit", (ev:any) => this.onValueInit(ev));
grid.addEventListener("dimensionInit", (ev:any) => this.onDimensionInit(ev));
}
The
DimensionInitandValueInitevents are emitted for each value and dimension defined in thepivotConfigurationproperty.
- In the
ValueInitevent handler set all custom aggregators, formatters and styles:
public onValueInit(event: any) {
const value: IgcPivotValue = event.detail;
if (value.member === 'AmountofSale') {
value.aggregate.aggregator = this.totalSale;
value.aggregateList?.forEach((aggr: any) => {
switch (aggr.key) {
case 'SUM':
aggr.aggregator = this.totalSale;
break;
case 'MIN':
aggr.aggregator = this.totalMin;
break;
case 'MAX':
aggr.aggregator = this.totalMax;
break;
}
});
} else if (value.member === 'Value') {
value.formatter = (value: any) => value ? '$' + parseFloat(value).toFixed(3) : undefined;
value.styles.upFontValue = (rowData: any, columnKey: any): boolean => parseFloat(rowData.aggregationValues.get(columnKey.field)) > 150
value.styles.downFontValue = (rowData: any, columnKey: any): boolean => parseFloat(rowData.aggregationValues.get(columnKey.field)) <= 150;
}
}
- In the
DimensionInitevent handler set all custommemberFunctionimplementations:
public onDimensionInit(event: any) {
const dim: IgcPivotDimension = event.detail;
switch (dim.memberName) {
case 'AllProducts':
dim.memberFunction = () => 'All Products';
break;
case 'ProductCategory':
dim.memberFunction = (data: any) => data.ProductName;
break;
case 'City':
dim.memberFunction = (data: any) => data.City;
break;
case 'SellerName':
dim.memberFunction = (data: any) => data.SellerName;
break;
}
}
Demo
Restoring Pivot Strategies
IgcGridStateComponent will not persist neither remote pivot operations nor custom dimension strategies.
Restoring any of these can be achieved with code on application level. The IgcGridStateComponent 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:
StateParsedis only emitted when we are usingSetStatewith string argument.
- Establezca una estrategia de clasificación personalizada y estrategias personalizadas de dimensiones de filas y columnas dinámicas:
public pivotConfiguration: IgcPivotConfiguration = {
columnStrategy: IgcNoopPivotDimensionsStrategy.instance(),
rowStrategy: IgcNoopPivotDimensionsStrategy.instance(),
columns: [...],
rows: [...],
values: [...],
filters: [...]
};
private gridState: IgcGridStateComponent;
constructor() {
var grid = document.getElementById("grid") as IgcPivotGridComponent;
this.gridState = document.getElementById('gridState') as IgcGridStateComponent;
grid.pivotConfiguration = this.pivotConfiguration;
PivotNoopData.getData().then((value) => {
grid.data = value;
});
this.gridState.addEventListener('stateParsed', (ev:any) => this.stateParsedHandler(ev) );
}
- Restaurar el estado de la
LocalStoragey aplicar las estrategias personalizadas se presenta de la siguiente manera:
public restoreGridState() {
const state = window.localStorage.getItem(this.stateKey);
if (state) {
this.gridState.applyStateFromString(state);
}
}
public stateParsedHandler(ev: any) {
const parsedState = ev.detail;
parsedState.pivotConfiguration.rowStrategy = IgcNoopPivotDimensionsStrategy.instance();
parsedState.pivotConfiguration.columnStrategy = IgcNoopPivotDimensionsStrategy.instance();
}
Limitations
getStatemethod uses JSON.stringify() method to convert the original objects to a JSON string. JSON.stringify() does not support Functions, thats why theIgcGridStateComponentdirective will ignore the pivot dimensionmemberFunction, pivot valuesmember,formatter, customaggregatefunctions,stylesand pivot configuration strategies:columnStrategyandrowStrategy.