Syncing the Sort State Between Grid Group and Column Headers
Environment
| Product | Progress® Kendo UI for Angular Grid |
Description
The Kendo UI for Angular Grid does not sync the sort between the component's column and group headers. This leads to some misleading and ambiguous UI/UX since the arrows in the group header and the respective column header may point in different directions. How can I sync the sort so that the arrows in the two headers indicate the same direction?
Solution
-
Create a custom function that accepts the current
Stateof theGridas a parameter. Use the arrays ofGroupDescriptorandSortDescriptorobjects that theStateprovides to normalize the sorting and grouping applied to the component.tsexport function syncSort(state: State, oldState: State = state): State { let group = state.group || []; if (group.length === 0) { return state; } let sort = state.sort || []; const sortedFields = new Set( sort.filter((desc) => desc.dir).map((desc) => desc.field) ); const sortChange = oldState.sort !== state.sort; group = state.group.map((group) => { const field = group.field; const isSorted = sortedFields.has(field); const sortDir = isSorted ? sort.find((desc) => desc.field === field).dir : 'asc'; const groupDir = group.dir || sortDir; const dir = sortChange ? sortDir : groupDir; return { field, dir }; }); ... } -
To sync the directions of the sorting and grouping features, create a new object with the two normalized descriptors.
tsexport function syncSort(state: State, oldState: State = state): State { ... const groupedFields = new Set(group.map((group) => group.field)); const sortGroups = group.map((group) => ({ field: group.field, dir: group.dir, })); const sortFields = sort.filter((sort) => !groupedFields.has(sort.field)); sort = [...sortGroups, ...sortFields]; return { ...state, group, sort }; } -
To sync the direction between the initial sorting and grouping that is applied to the
Grid, call the already created custom function during the initialization of the component.tspublic ngOnInit(): void { this.state = syncSort(this.state); this.loadProducts(); } -
To sync the directions between the grouping and sorting that are applied to the component, handle the
DataStateChangeEventevent of theGrid.tspublic dataStateChange(state: State): void { this.state = syncSort(state, this.state); this.loadProducts(); }
The following example demonstrates the suggested approach in action.