Blazor Pivot Grid State Persistence

    The Ignite UI for Blazor State Persistence in Blazor Pivot Grid allows developers to easily save and restore the grid state. When the IgbGridState is applied on the Blazor IgbPivotGrid, it exposes the GetStateAsStringAsync and ApplyStateFromStringAsync methods that developers can use to achieve state persistence in any scenario.

    Supported Features

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

    • Sorting
    • Filtering
    • CellSelection
    • ColumnSelection
    • Expansion
    • IgbPivotConfiguration
      • Pivot Configuration properties defined by the IPivotConfiguration interface.
      • 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.

    Usage

    DevuelveGetStateAsStringAsync 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.

    <IgbPivotGrid>
        <IgbGridState @ref="gridState"></IgbGridState>
    </IgbPivotGrid>
    
    @code {
        // get all features` state in a serialized JSON string
        string stateString = gridState.GetStateAsStringAsync(new string[0]);
    
        // get the sorting and filtering expressions
        string sortingFilteringStates = gridState.GetStateAsStringAsync(new string[] { "sorting", "filtering" });
    }
    

    ApplyStateFromStringAsync- 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.ApplyStateFromStringAsync(gridStateString, new string[0]);
    gridState.ApplyStateFromStringAsync(sortingFilteringStates, new string[0])
    

    ElOptions objeto implementa laIgbGridStateOptions 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.GetStateAsStringAsync Los métodos no pondrán el estado de estas características en el valor devuelto yApplyStateFromStringAsync los métodos no restaurarán el estado para ellas.

    gridState.Options = new IgbGridStateOptions
        {
            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:

    @using IgniteUI.Blazor.Controls
    @using Newtonsoft.Json
    @implements IDisposable
    
    @inject IJSRuntime JS
    @inject NavigationManager Navigation
    
    <IgbPivotGrid Rendered="OnGridRendered">
        <IgbGridState @ref="gridState"></IgbGridState>
        <IgbColumn Field="ContactName" Header="Name" MinWidth="200px" ></IgbColumn>
        <IgbColumn Field="ContactTitle" Header="Title" MinWidth="200px" Sortable="true" Filterable="true" Groupable="true"></IgbColumn>
        <IgbColumn Field="CompanyName" Header="Company" MinWidth="200px" Sortable="true" Filterable="true" Groupable="true"></IgbColumn>
    </IgbPivotGrid>
    
    @code {
        protected override void OnAfterRender(bool firstRender)
        {
            Navigation.LocationChanged += OnLocationChanged;
        }
    
        void OnLocationChanged(object sender, LocationChangedEventArgs e)
        {
            SaveGridState();
        }
    
        void IDisposable.Dispose()
        {
            // Unsubscribe from the event when our component is disposed
            Navigation.LocationChanged -= OnLocationChanged;
        }
    
        void OnGridRendered()
        {
            RestoreGridState();
        }
    
        async void SaveGridState() {
            string state = gridState.GetStateAsStringAsync(new string[0]);
            await JS.InvokeVoidAsync("window.localStorage.setItem", "grid-state", state);
        }
    
        async void RestoreGridState() {
            string state = await JS.InvokeAsync<string>("window.localStorage.getItem", "grid-state");
            if (state) {
                gridState.ApplyStateFromStringAsync(state, new string[0]);
            }
        }
    }
    

    Restoring Pivot Configuration

    IgbGridState 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 IgbPivotGrid 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:
        <IgbPivotGrid
            @ref="grid"
            Width="95%"
            Height="500px"
            PivotConfiguration="PivotConfiguration"
            ValueInitScript="OnValueInit">
        </IgbPivotGrid>
    

    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:
    // In Javascript
    const totalSale = (members, data) => {
        return data.reduce((accumulator, value) => accumulator + value.ProductUnitPrice * value.NumberOfUnits, 0);
    };
    
    const totalMin = (members, data) => {
        let min = 0;
        if (data.length === 1) {
            min = data[0].ProductUnitPrice * data[0].NumberOfUnits;
        } else if (data.length > 1) {
            const mappedData = data.map(x => x.ProductUnitPrice * x.NumberOfUnits);
            min = mappedData.reduce((a, b) => Math.min(a, b));
        }
        return min;
    };
    
    const totalMax = (members, data) => {
        let max = 0;
        if (data.length === 1) {
            max = data[0].ProductUnitPrice * data[0].NumberOfUnits;
        } else if (data.length > 1) {
            const mappedData = data.map(x => x.ProductUnitPrice * x.NumberOfUnits);
            max = mappedData.reduce((a, b) => Math.max(a, b));
        }
        return max;
    };
    
    igRegisterScript("OnValueInit", (args) => {
        const value = args.detail;
        if (value.member === "AmountOfSale") {
          value.aggregate.aggregator = totalSale;
          value.aggregateList?.forEach((aggr) => {
            switch (aggr.key) {
              case "SUM":
                aggr.aggregator = totalSale;
                break;
              case "MIN":
                aggr.aggregator = totalMin;
                break;
              case "MAX":
                aggr.aggregator = totalMax;
                break;
            }
          });
        }
    }, false);
    

    Demo

    Limitations

    • GetState method uses JSON.stringify() method to convert the original objects to a JSON string. JSON.stringify() does not support Functions, thats why the IgbGridState directive will ignore the pivot dimension MemberFunction, pivot values Member, Formatter, custom Aggregate functions, Styles and pivot configuration strategies: ColumnStrategy and RowStrategy.