Angular Pivot Grid State Persistence

    A diretriz igxGridState permite que desenvolvedores salvem e restaurem facilmente o estado da grade. Quando aIgxGridState diretiva é aplicada na grade, ela expõe osgetState métodos esetState que os desenvolvedores podem usar para alcançar persistência de estado em qualquer cenário.

    Supported Features

    IgxGridStateA Diretiva suporta salvar e restaurar o estado das seguintes características:

    Note

    ORow Selection recurso exige que aprimaryKey propriedade seja definida, para que ela possa ser armazenada/restaurada corretamente.

    Usage

    getState- Esse método retorna o estado da grade em uma string JSON serializada, para que os desenvolvedores possam simplesmente pegá-lo e salvá-lo em qualquer armazenamento de dados (banco de dados, nuvem, localStorage do navegador, etc). O método aceita o primeiro parâmetroserialize opcional, que determina segetState retornará umIGridState objeto ou uma string JSON serializada. O desenvolvedor pode optar por obter apenas o estado de uma ou das funcionalidades específicas, passando o nome da funcionalidade, ou um array com nomes de funcionalidades 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- OsetState método aceita a string ouIGridState objeto JSON serializado como argumento e restaurará o estado de cada característica encontrada no objeto/string JSON.

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

    options- Ooptions objeto implementa aIGridStateOptions interface, ou seja, para cada chave, que é o nome de uma determinada característica, existe o valor booleano indicando se esse estado da característica será rastreado.getState O método não colocará o estado desses recursos no valor retornado esetState o método não restaurará o estado para ele.

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

    As APIs simples de usar permitem alcançar uma funcionalidade completa de persistência de estado em apenas algumas linhas de código. Copie e cole o código abaixo– ele salvará o estado da grade no objeto do navegadorsessionStorage toda vez que o usuário sair da página atual. Sempre que o usuário retorna à página principal, o estado da grade será restaurado. Não é mais necessário configurar aquelas expressões avançadas de filtragem e ordenação toda vez para obter os dados que você quer – faça isso uma vez e o código abaixo faça o restante para seus usuários:

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

    stateParsedé emitido apenas quando estamos usandosetState com argumento de string.

    • Defina a estratégia de classificação personalizada e as estratégias personalizadas de dimensão de linha e coluna dinâmica:
    <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 o estado dosessionStorage e aplicar as estratégias personalizadas é o seguinte:
    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