Angular Pivot Grid State Persistence
igxGridState 지침은 개발자가 그리드 상태를 쉽게 저장하고 복원할 수 있게 합니다.IgxGridState이 지시가 그리드에 적용되면, 개발자가 어떤 상황에서도 상태 지속성을 달성하기 위해 사용할 수 있는 방법들과getStatesetState 메서드가 노출됩니다.
Supported Features
IgxGridState지침은 다음 기능들의 상태 저장 및 복원을 지원합니다:
SortingFilteringCell SelectionRow SelectionColumn SelectionExpansionPivot Configuration- Pivot Configuration properties defined by the
IPivotConfigurationinterface. - 피벗 차원 및 값 기능은 애플리케이션 수준 코드를 사용하여 복원됩니다. 피벗 구성 복원 섹션을 참조하세요.
- 피벗 행 및 열 전략도 애플리케이션 수준 코드를 사용하여 복원됩니다. 피벗 전략 복원 섹션을 참조하세요.
- Pivot Configuration properties defined by the
Note
Row Selection이 기능은 속성을 설정해야primaryKey 올바르게 저장/복원할 수 있습니다.
Usage
getState- 이 메서드는 그리드 상태를 직렬화된 JSON 문자열로 반환하므로, 개발자는 이를 데이터베이스, 클라우드, 브라우저 localStorage 등 어떤 데이터 저장소에도 저장할 수 있습니다. 이 메서드는 첫 번째 선택적 매개변수를 수용합니다serialize, 이 조건은getState 돌아올 것이다IGridState 객체나 직렬화된 JSON 문자열을 사용한다. 개발자는 기능 이름이나 기능 이름이 포함된 배열을 두 번째 인자로 입력하여 특정 기능의 상태만 얻을 수 있습니다.
// 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- 메서드는setState 직렬화된 JSON 문자열 또는IGridState 객체를 인수로 받아들이며, 객체/JSON 문자열 내 각 기능의 상태를 복원합니다.
state.setState(gridState);
state.setState(sortingFilteringStates)
options- 객체는options 인터페이스를 구현합니다IGridStateOptions. 즉, 각 키(특정 기능의 이름)마다 이 기능 상태가 추적될지 여부를 나타내는 불리언 값이 있습니다.getState 메서드는 반환된 값에 이러한 특징들의 상태를 넣지 않으며,setState 메서드는 해당 상태 복원도 하지 않습니다.
public options = { cellSelection: false; sorting: false; }
<igx-pivot-grid [igxGridState]="options"></igx-pivot-grid>
사용하기 쉬운 단일 포인트 API는 단 몇 줄의 코드만으로 완전한 상태 영속성을 달성할 수 있게 합니다. 아래에서 코드를 복사해서 붙여넣으세요. 사용자가 현재 페이지를 떠날 때마다 브라우저sessionStorage 객체에 그리드 상태를 저장합니다. 사용자가 메인 페이지로 돌아올 때마다 그리드 상태가 복원됩니다. 매번 복잡한 고급 필터링과 정렬 표현식을 설정할 필요가 없고, 한 번만 설정하면 아래 코드가 나머지 작업을 사용자 대신 처리해 주세요:
// 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
dimensionInitandvalueInitevents:
<igx-pivot-grid #grid1 [data]="data" [pivotConfiguration]="pivotConfig" [igxGridState]="options"
(valueInit)='onValueInit($event)' (dimensionInit)='onDimensionInit($event)'>
</igx-pivot-grid>
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(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
dimensionInitevent handler set all custommemberFunctionimplementations:
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는 문자열 인수와 함께 사용할setState때만 방출됩니다.
- 사용자 정의 정렬 전략과 사용자 정의 피벗 열 및 행 차원 전략을 설정합니다.
<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: [...]
};
- 상태에서
sessionStorage복원하고 사용자 지정 전략을 적용하는 방법은 다음과 같습니다:
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
getStatemethod uses JSON.stringify() method to convert the original objects to a JSON string. JSON.stringify() does not support Functions, thats why theIgxGridStatedirective will ignore the pivot dimensionmemberFunction, pivot valuesmember,formatter, customaggregatefunctions,stylesand pivot configuration strategies:columnStrategyandrowStrategy.