Web Components 피벗 그리드 상태 지속성

    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

    IgcGridStateComponent다음 기능들의 상태 저장 및 복원을 지원합니다:

    • Sorting
    • Filtering
    • CellSelection
    • ColumnSelection
    • Expansion
    • IgcPivotConfiguration
      • Pivot Configuration properties defined by the IPivotConfiguration interface.
      • 피벗 차원 및 값 기능은 애플리케이션 수준 코드를 사용하여 복원됩니다. 피벗 구성 복원 섹션을 참조하세요.
      • 피벗 행 및 열 전략도 애플리케이션 수준 코드를 사용하여 복원됩니다. 피벗 전략 복원 섹션을 참조하세요.

    Usage

    이 메서드는getState 모든 상태 정보를 포함하는 객체의IgcGridStateInfo 그리드 상태를 반환합니다. 이를 구하기 위해 추가 절차가 필요할 수 있습니다.

    이 도구는getStateAsString 직렬화된 JSON 문자열을 반환하기 때문에 개발자들은 이를 가져와 데이터베이스, 클라우드, 브라우저 localStorage 등 어떤 데이터 저장소에도 저장할 수 있습니다.

    개발자는 기능 이름이 있는 배열을 인수로 전달하여 특정 기능에 대한 상태만 가져오도록 선택할 수 있습니다. 빈 배열은 기본 상태 옵션을 사용하게 됩니다.

    <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- 메서드는 객체를IgcGridStateInfo 인자로 받아들이며, 객체나 지정된 특징에서 발견된 각 특징의 상태를 두 번째 인자로 복원합니다.

    applyStateFromString- 메서드는 직렬화된 JSON 문자열을 인자로 받아들이며, JSON 문자열이나 지정된 두 번째 인자로 지정된 각 특징의 상태를 복원합니다.

    gridState.applyState(gridState);
    gridState.applyStateFromString(gridStateString);
    gridState.applyState(sortingFilteringStates)
    

    객체는options 인터페이스를 구현하므로IgcGridStateOptions, 각 키(특정 기능의 이름)마다 해당 기능 상태가 추적될지 여부를 나타내는 불리언 값이 있습니다.getState /getStateAsString 메서드는 이 특징들의 상태를 반환된 값에 넣지 않으며,applyStateapplyStateFromString 메서드는 해당 특징들의 상태를 복원하지 않습니다.

    gridState.options = { cellSelection: false, sorting: false };
    

    사용하기 쉬운 단일 포인트 API는 단 몇 줄의 코드만으로 완전한 상태 영속성을 달성할 수 있게 합니다. 아래에서 코드를 복사해서 붙여넣으세요. 사용자가 현재 페이지를 떠날 때마다 브라우저LocalStorage 객체에 그리드 상태를 저장합니다. 사용자가 메인 페이지로 돌아올 때마다 그리드 상태가 복원됩니다. 매번 복잡한 고급 필터링과 정렬 표현식을 설정할 필요가 없고, 한 번만 설정하면 아래 코드가 나머지 작업을 사용자 대신 처리해 주세요:

    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 DimensionInit and ValueInit events:
     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 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(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 DimensionInit event handler set all custom memberFunction implementations:
    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:

    StateParsed is only emitted when we are using SetState with string argument.

    • 사용자 정의 정렬 전략과 사용자 정의 피벗 열 및 행 차원 전략을 설정합니다.
    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) );
    }
    
    • 상태에서LocalStorage 복원하고 사용자 지정 전략을 적용하는 방법은 다음과 같습니다:
    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