-
-
Notifications
You must be signed in to change notification settings - Fork 119
/
grid-draggrouping.component.ts
455 lines (418 loc) · 15.2 KB
/
grid-draggrouping.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import { TextExportService } from '@slickgrid-universal/text-export';
import {
AngularGridInstance,
Aggregators,
Column,
Editors,
FieldType,
FileType,
Filters,
Formatters,
GridOption,
Grouping,
GroupingGetterFunction,
GroupTotalFormatters,
SortDirectionNumber,
SortComparers,
} from './../modules/angular-slickgrid';
@Component({
templateUrl: './grid-draggrouping.component.html',
})
export class GridDraggableGroupingComponent implements OnInit, OnDestroy {
private _darkMode = false;
title = 'Example 19: Draggable Grouping & Aggregators';
subTitle = `
<ul>
<li><a href="https://ghiscoding.gitbook.io/angular-slickgrid/grid-functionalities/grouping-and-aggregators" target="_blank">Wiki docs</a></li>
<li>This example shows 3 ways of grouping</li>
<ol>
<li>Drag any Column Header on the top placeholder to group by that column (support moti-columns grouping by adding more columns to the drop area).</li>
<li>Use buttons and defined functions to group by wichever field you want</li>
<li>Use the Select dropdown to group, the position of the Selects represent the grouping level</li>
</ol>
<li>Fully dynamic and interactive multi-level grouping with filtering and aggregates ovor 50'000 items</li>
<li>Each grouping level can have its own aggregates (over child rows, child groups, or all descendant rows)..</li>
<li>Use "Aggregators" and "GroupTotalFormatters" directly from Angular-Slickgrid</li>
</ul>
`;
angularGrid!: AngularGridInstance;
columnDefinitions!: Column[];
dataset!: any[];
dataviewObj: any;
draggableGroupingPlugin: any;
durationOrderByCount = false;
gridObj: any;
gridOptions!: GridOption;
processing = false;
selectedGroupingFields: Array<string | GroupingGetterFunction> = ['', '', ''];
excelExportService = new ExcelExportService();
textExportService = new TextExportService();
constructor() {
// define the grid options & columns and then create the grid itself
this.loadData(500);
this.defineGrid();
}
ngOnInit(): void {
// populate the dataset once the grid is ready
this.defineGrid();
}
ngOnDestroy() {
document.querySelector('.panel-wm-content')!.classList.remove('dark-mode');
document.querySelector<HTMLDivElement>('#demo-container')!.dataset.bsTheme = 'light';
}
angularGridReady(angularGrid: AngularGridInstance) {
this.angularGrid = angularGrid;
this.gridObj = angularGrid.slickGrid; // grid object
this.dataviewObj = angularGrid.dataView;
}
/* Define grid Options and Columns */
defineGrid() {
this.columnDefinitions = [
{
id: 'title',
name: 'Title',
field: 'title',
columnGroup: 'Common Factor',
width: 70,
minWidth: 50,
cssClass: 'cell-title',
filterable: true,
sortable: true,
grouping: {
getter: 'title',
formatter: (g) => `Title: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('cost')],
aggregateCollapsed: false,
collapsed: false,
},
},
{
id: 'duration',
name: 'Duration',
field: 'duration',
columnGroup: 'Common Factor',
width: 70,
sortable: true,
filterable: true,
editor: {
model: Editors.float,
// required: true,
decimal: 2,
valueStep: 1,
maxValue: 10000,
alwaysSaveOnEnterKey: true,
},
filter: { model: Filters.slider, operator: '>=' },
type: FieldType.number,
groupTotalsFormatter: GroupTotalFormatters.sumTotals,
grouping: {
getter: 'duration',
formatter: (g) => `Duration: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
comparer: (a, b) => {
return this.durationOrderByCount
? a.count - b.count
: SortComparers.numeric(a.value, b.value, SortDirectionNumber.asc);
},
aggregators: [new Aggregators.Sum('duration'), new Aggregators.Sum('cost')],
aggregateCollapsed: false,
collapsed: false,
},
},
{
id: 'start',
name: 'Start',
field: 'start',
columnGroup: 'Period',
minWidth: 60,
sortable: true,
filterable: true,
filter: { model: Filters.compoundDate },
formatter: Formatters.dateIso,
type: FieldType.dateUtc,
outputType: FieldType.dateIso,
exportWithFormatter: true,
grouping: {
getter: 'start',
formatter: (g) => `Start: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('cost')],
aggregateCollapsed: false,
collapsed: false,
},
},
{
id: 'finish',
name: 'Finish',
field: 'finish',
columnGroup: 'Period',
minWidth: 60,
sortable: true,
filterable: true,
filter: { model: Filters.compoundDate },
formatter: Formatters.dateIso,
type: FieldType.dateUtc,
outputType: FieldType.dateIso,
exportWithFormatter: true,
grouping: {
getter: 'finish',
formatter: (g) => `Finish: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('cost')],
aggregateCollapsed: false,
collapsed: false,
},
},
{
id: 'cost',
name: 'Cost',
field: 'cost',
columnGroup: 'Analysis',
width: 90,
sortable: true,
filterable: true,
filter: { model: Filters.compoundInput },
formatter: Formatters.dollar,
groupTotalsFormatter: GroupTotalFormatters.sumTotalsDollar,
type: FieldType.number,
grouping: {
getter: 'cost',
formatter: (g) => `Cost: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('cost')],
aggregateCollapsed: true,
collapsed: true,
},
},
{
id: 'percentComplete',
name: '% Complete',
field: 'percentComplete',
columnGroup: 'Analysis',
minWidth: 70,
width: 90,
formatter: Formatters.percentCompleteBar,
type: FieldType.number,
filterable: true,
filter: { model: Filters.compoundSlider },
sortable: true,
groupTotalsFormatter: GroupTotalFormatters.avgTotalsPercentage,
grouping: {
getter: 'percentComplete',
formatter: (g) => `% Complete: ${g.value} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('cost')],
aggregateCollapsed: false,
collapsed: false,
},
params: { groupFormatterPrefix: '<i>Avg</i>: ' },
},
{
id: 'effortDriven',
name: 'Effort-Driven',
field: 'effortDriven',
columnGroup: 'Analysis',
width: 80,
minWidth: 20,
maxWidth: 100,
cssClass: 'cell-effort-driven',
sortable: true,
filterable: true,
filter: {
collection: [
{ value: '', label: '' },
{ value: true, label: 'True' },
{ value: false, label: 'False' },
],
model: Filters.singleSelect,
},
formatter: Formatters.checkmarkMaterial,
grouping: {
getter: 'effortDriven',
formatter: (g) => `Effort-Driven: ${g.value ? 'True' : 'False'} <span class="text-primary">(${g.count} items)</span>`,
aggregators: [new Aggregators.Sum('duration'), new Aggregators.Sum('cost')],
collapsed: false,
},
},
];
this.gridOptions = {
autoResize: {
container: '#demo-container',
rightPadding: 10,
},
enableDraggableGrouping: true,
autoEdit: true, // true single click (false for double-click)
autoCommitEdit: true,
editable: true,
enableCellNavigation: true,
// pre-header will include our Header Grouping (i.e. "Common Factor")
// Draggable Grouping could be located in either the Pre-Header OR the new Top-Header
createPreHeaderPanel: true,
showPreHeaderPanel: true,
preHeaderPanelHeight: 30,
// when Top-Header is created, it will be used by the Draggable Grouping (otherwise the Pre-Header will be used)
createTopHeaderPanel: true,
showTopHeaderPanel: true,
topHeaderPanelHeight: 35,
showCustomFooter: true,
enableFiltering: true,
// you could debounce/throttle the input text filter if you have lots of data
// filterTypingDebounce: 250,
enableSorting: true,
textExportOptions: {
sanitizeDataExport: true,
},
gridMenu: {
onCommand: (e, args) => {
if (args.command === 'toggle-preheader') {
// in addition to the grid menu pre-header toggling (internally), we will also clear grouping
this.clearGrouping();
}
},
},
draggableGrouping: {
dropPlaceHolderText: 'Drop a column header here to group by the column',
// groupIconCssClass: 'mdi mdi-drag-vertical',
deleteIconCssClass: 'mdi mdi-close text-color-danger',
sortAscIconCssClass: 'mdi mdi-arrow-up',
sortDescIconCssClass: 'mdi mdi-arrow-down',
onGroupChanged: (e, args) => this.onGroupChanged(args),
onExtensionRegistered: (extension) => (this.draggableGroupingPlugin = extension),
},
darkMode: this._darkMode,
enableTextExport: true,
enableExcelExport: true,
excelExportOptions: { sanitizeDataExport: true },
externalResources: [this.excelExportService, this.textExportService],
};
this.loadData(500);
}
loadData(rowCount: number) {
// mock a dataset
const tmpData = [];
for (let i = 0; i < rowCount; i++) {
const randomYear = 2000 + Math.floor(Math.random() * 10);
const randomMonth = Math.floor(Math.random() * 11);
const randomDay = Math.floor(Math.random() * 29);
const randomPercent = Math.round(Math.random() * 100);
const randomCost = Math.round(Math.random() * 10000) / 100;
tmpData[i] = {
id: 'id_' + i,
num: i,
title: 'Task ' + i,
duration: Math.round(Math.random() * 100) + '',
percentComplete: randomPercent,
percentCompleteNumber: randomPercent,
start: new Date(randomYear, randomMonth, randomDay),
finish: new Date(randomYear, randomMonth + 1, randomDay),
cost: i % 33 === 0 ? -randomCost : randomCost,
effortDriven: i % 5 === 0,
};
}
this.dataset = tmpData;
}
clearGroupsAndSelects() {
this.clearGroupingSelects();
this.clearGrouping();
}
clearGrouping(invalidateRows = true) {
this.draggableGroupingPlugin?.clearDroppedGroups();
if (invalidateRows) {
this.gridObj?.invalidate(); // invalidate all rows and re-render
}
}
clearGroupingSelects() {
this.selectedGroupingFields.forEach((g, i) => (this.selectedGroupingFields[i] = ''));
}
collapseAllGroups() {
this.dataviewObj.collapseAllGroups();
}
expandAllGroups() {
this.dataviewObj.expandAllGroups();
}
exportToExcel() {
this.excelExportService.exportToExcel({
filename: 'Export',
format: FileType.xlsx,
});
}
groupByDurationOrderByCount(sortedByCount = false) {
this.durationOrderByCount = sortedByCount;
this.clearGrouping(false);
if (this.draggableGroupingPlugin?.setDroppedGroups) {
this.showPreHeader();
this.draggableGroupingPlugin.setDroppedGroups('duration');
// you need to manually add the sort icon(s) in UI
const sortColumns = sortedByCount ? [] : [{ columnId: 'duration', sortAsc: true }];
this.gridObj?.setSortColumns(sortColumns);
this.gridObj?.invalidate(); // invalidate all rows and re-render
}
}
groupByDurationEffortDriven() {
this.clearGrouping(false);
if (this.draggableGroupingPlugin?.setDroppedGroups) {
this.showPreHeader();
this.draggableGroupingPlugin.setDroppedGroups(['duration', 'effortDriven']);
this.gridObj?.invalidate(); // invalidate all rows and re-render
}
}
groupByFieldName(_fieldName: string, _index: number) {
this.clearGrouping();
if (this.draggableGroupingPlugin && this.draggableGroupingPlugin.setDroppedGroups) {
// get the field names from Group By select(s) dropdown, but filter out any empty fields
const groupedFields = this.selectedGroupingFields.filter((g) => g !== '');
this.showPreHeader();
this.draggableGroupingPlugin.setDroppedGroups(groupedFields);
this.gridObj.invalidate(); // invalidate all rows and re-render
}
}
onGroupChanged(change: { caller?: string; groupColumns: Grouping[] }) {
// the "caller" property might not be in the SlickGrid core lib yet, reference PR https://github.com/6pac/SlickGrid/pull/303
const caller = (change && change.caller) || [];
const groups = (change && change.groupColumns) || [];
if (Array.isArray(this.selectedGroupingFields) && Array.isArray(groups) && groups.length > 0) {
// update all Group By select dropdown
this.selectedGroupingFields.forEach((g, i) => (this.selectedGroupingFields[i] = (groups[i] && groups[i].getter) || ''));
} else if (groups.length === 0 && caller === 'remove-group') {
this.clearGroupingSelects();
}
}
onCellChanged() {
// when user changes a cell, we need to advise the DataView for the grouping to update its totals
this.angularGrid.dataView?.refresh();
}
showPreHeader() {
this.gridObj.setPreHeaderPanelVisibility(true);
}
selectTrackByFn(index: number, _item: any) {
return index;
}
setFiltersDynamically() {
// we can Set Filters Dynamically (or different filters) afterward through the FilterService
this.angularGrid.filterService.updateFilters([
{ columnId: 'percentComplete', operator: '>=', searchTerms: ['55'] },
{ columnId: 'cost', operator: '<', searchTerms: ['80'] },
]);
}
setSortingDynamically() {
this.angularGrid.sortService.updateSorting([
// orders matter, whichever is first in array will be the first sorted column
{ columnId: 'percentComplete', direction: 'ASC' },
]);
}
toggleDraggableGroupingRow() {
this.clearGrouping();
this.gridObj.setTopHeaderPanelVisibility(!this.gridObj.getOptions().showTopHeaderPanel);
}
toggleDarkMode() {
this._darkMode = !this._darkMode;
this.toggleBodyBackground();
this.angularGrid.slickGrid?.setOptions({ darkMode: this._darkMode });
}
toggleBodyBackground() {
if (this._darkMode) {
document.querySelector<HTMLDivElement>('.panel-wm-content')!.classList.add('dark-mode');
document.querySelector<HTMLDivElement>('#demo-container')!.dataset.bsTheme = 'dark';
} else {
document.querySelector('.panel-wm-content')!.classList.remove('dark-mode');
document.querySelector<HTMLDivElement>('#demo-container')!.dataset.bsTheme = 'light';
}
}
}