Angular Pivot Grid State Persistence

    La directiva igxGridState permite a los desarrolladores guardar y restaurar fácilmente el estado de la cuadrícula. Cuando laIgxGridState directiva se aplica a la red, expone losgetState métodossetState y que los desarrolladores pueden utilizar para lograr la persistencia de estado en cualquier escenario.

    Supported Features

    IgxGridStateDirectiva permite guardar y restaurar el estado de las siguientes características:

    • Sorting
    • Filtering
    • Cell Selection
    • Row Selection
    • Column Selection
    • Expansion
    • Pivot Configuration
    Note

    LaRow Selection característica requiere que laprimaryKey propiedad esté establecida para poder almacenarse o restaurarse correctamente.

    Usage

    getState- Este método devuelve el estado de la cuadrícula en una cadena JSON serializada, de modo que los desarrolladores pueden simplemente tomarlo y guardarlo en cualquier almacenamiento de datos (base de datos, nube, localStorage del navegador, etc.). El método acepta el primer parámetroserialize opcional, que determina sigetState devolverá unIGridState objeto o una cadena JSON serializada. El desarrollador puede elegir obtener solo el estado de una o ciertas características, pasando el nombre de la característica, o un array con nombres de características como segundo argumento.

    // 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- ElsetState método acepta la cadena uIGridState objeto JSON serializado como argumento y restaurará el estado de cada característica encontrada en el objeto/cadena JSON.

    state.setState(gridState);
    state.setState(sortingFilteringStates)
    

    options- Eloptions objeto implementa laIGridStateOptions 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 El método no pondrá el estado de estas características en el valor devuelto ysetState el método no restaurará el estado para ellas.

    public options =  { cellSelection: false; sorting: false; }
    
    <igx-pivot-grid [igxGridState]="options"></igx-pivot-grid>
    

    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 navegadorsessionStorage 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:

    // 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 Pivot Configuration

    IgxGridState 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 IgxPivotGrid 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 dimensionInit and valueInit events:
    <igx-pivot-grid #grid1 [data]="data" [pivotConfiguration]="pivotConfig" [igxGridState]="options"
        (valueInit)='onValueInit($event)' (dimensionInit)='onDimensionInit($event)'>
    </igx-pivot-grid>
    

    The dimensionInit and valueInit events are emitted for each value and dimension defined in the pivotConfiguration property.

    • In the valueInit event handler set all custom aggregators, formatters and styles:
    public onValueInit(value: IPivotValue) {
        // Needed only for custom aggregators, formatter or styles.
        if (value.member === 'AmountofSale') {
            value.aggregate.aggregator = IgxTotalSaleAggregate.totalSale;
            value.aggregateList?.forEach((aggr: IPivotAggregator) => {
                switch (aggr.key) {
                    case 'SUM':
                        aggr.aggregator = IgxTotalSaleAggregate.totalSale;
                        break;
                    case 'MIN':
                        aggr.aggregator = IgxTotalSaleAggregate.totalMin;
                        break;
                    case 'MAX':
                        aggr.aggregator = IgxTotalSaleAggregate.totalMax;
                        break;
                }
            });
        } else if (value.member === 'Value') {
            value.formatter = (value) => 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 dimensionInit event handler set all custom memberFunction implementations:
    public onDimensionInit(dim: IPivotDimension) {
        switch (dim.memberName) {
            case 'AllProducts':
                dim.memberFunction = () => 'All Products';
                break;
            case 'ProductCategory':
                dim.memberFunction = (data) => data.Product.Name;
                break;
            case 'City':
                dim.memberFunction = (data) => data.Seller.City;
                break;
            case 'SellerName':
                dim.memberFunction = (data) => data.Seller.Name;
                break;
        }
    }
    

    Restoring Pivot Strategies

    IgxGridState will not persist neither remote pivot operations nor custom dimension strategies (For further information see Pivot 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:

    stateParsedsolo se emite cuando usamossetState con argumento de cadena.

    • Establezca una estrategia de clasificación personalizada y estrategias personalizadas de dimensiones de filas y columnas dinámicas:
    <igx-pivot-grid #grid [data]="data" [pivotConfiguration]="pivotConfigHierarchy" [defaultExpandState]='true'
        [igxGridState]="options" [sortStrategy]="customStrategy" [pivotUI]='{ showConfiguration: false }' [superCompactMode]="true" [height]="'500px'">
    </igx-pivot-grid>
    
    @ViewChild(IgxGridStateDirective, { static: true })
    public state!: IgxGridStateDirective;
    
    public customStrategy = NoopSortingStrategy.instance();
    public options: IGridStateOptions = {...};
    public pivotConfigHierarchy: IPivotConfiguration = {
        columnStrategy: NoopPivotDimensionsStrategy.instance(),
        rowStrategy: NoopPivotDimensionsStrategy.instance(),
        columns: [...],
        rows: [...],
        values: [...],
        filters: [...]
    };
    
    • Restaurar el estado de lasessionStorage y aplicar las estrategias personalizadas se presenta de la siguiente manera:
    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());
            parsedState.pivotConfiguration.rowStrategy = NoopPivotDimensionsStrategy.instance();
            parsedState.pivotConfiguration.columnStrategy = NoopPivotDimensionsStrategy.instance();
        });
        this.state.setState(state as string);
    }
    

    Limitations

    API References

    Additional Resources