-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
table.spec.ts
811 lines (676 loc) · 30 KB
/
table.spec.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {Component, ViewChild} from '@angular/core';
import {CdkTable} from './table';
import {CollectionViewer, DataSource} from './data-source';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Observable} from 'rxjs/Observable';
import {combineLatest} from 'rxjs/observable/combineLatest';
import {CdkTableModule} from './index';
import {map} from 'rxjs/operator/map';
import {getTableDuplicateColumnNameError, getTableUnknownColumnError} from './table-errors';
describe('CdkTable', () => {
let fixture: ComponentFixture<SimpleCdkTableApp>;
let component: SimpleCdkTableApp;
let dataSource: FakeDataSource;
let table: CdkTable<any>;
let tableElement: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CdkTableModule],
declarations: [
SimpleCdkTableApp,
DynamicDataSourceCdkTableApp,
CustomRoleCdkTableApp,
TrackByCdkTableApp,
DynamicColumnDefinitionsCdkTableApp,
RowContextCdkTableApp,
DuplicateColumnDefNameCdkTableApp,
MissingColumnDefCdkTableApp,
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SimpleCdkTableApp);
component = fixture.componentInstance;
dataSource = component.dataSource as FakeDataSource;
table = component.table;
tableElement = fixture.nativeElement.querySelector('cdk-table');
fixture.detectChanges();
});
describe('should initialize', () => {
it('with a connected data source', () => {
expect(table.dataSource).toBe(dataSource);
expect(dataSource.isConnected).toBe(true);
});
it('with a rendered header with the right number of header cells', () => {
const header = getHeaderRow(tableElement);
expect(header).not.toBe(undefined);
expect(header.classList).toContain('customHeaderRowClass');
expect(getHeaderCells(tableElement).length).toBe(component.columnsToRender.length);
});
it('with rendered rows with right number of row cells', () => {
const rows = getRows(tableElement);
expect(rows.length).toBe(dataSource.data.length);
rows.forEach(row => {
expect(row.classList).toContain('customRowClass');
expect(getCells(row).length).toBe(component.columnsToRender.length);
});
});
it('with column class names provided to header and data row cells', () => {
getHeaderCells(tableElement).forEach((headerCell, index) => {
expect(headerCell.classList).toContain(`cdk-column-${component.columnsToRender[index]}`);
});
getRows(tableElement).forEach(row => {
getCells(row).forEach((cell, index) => {
expect(cell.classList).toContain(`cdk-column-${component.columnsToRender[index]}`);
});
});
});
it('with the right accessibility roles', () => {
expect(tableElement.getAttribute('role')).toBe('grid');
expect(getHeaderRow(tableElement).getAttribute('role')).toBe('row');
getHeaderCells(tableElement).forEach(cell => {
expect(cell.getAttribute('role')).toBe('columnheader');
});
getRows(tableElement).forEach(row => {
expect(row.getAttribute('role')).toBe('row');
getCells(row).forEach(cell => {
expect(cell.getAttribute('role')).toBe('gridcell');
});
});
});
});
it('should disconnect the data source when table is destroyed', () => {
expect(dataSource.isConnected).toBe(true);
fixture.destroy();
expect(dataSource.isConnected).toBe(false);
});
it('should not clobber an existing table role', () => {
fixture = TestBed.createComponent(CustomRoleCdkTableApp);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('cdk-table').getAttribute('role')).toBe('treegrid');
});
it('should throw an error if two column definitions have the same name', () => {
expect(() => TestBed.createComponent(DuplicateColumnDefNameCdkTableApp).detectChanges())
.toThrowError(getTableDuplicateColumnNameError('column_a').message);
});
it('should throw an error if a column definition is requested but not defined', () => {
expect(() => TestBed.createComponent(MissingColumnDefCdkTableApp).detectChanges())
.toThrowError(getTableUnknownColumnError('column_a').message);
});
it('should be able to dynamically add/remove column definitions', () => {
const dynamicColumnDefFixture = TestBed.createComponent(DynamicColumnDefinitionsCdkTableApp);
dynamicColumnDefFixture.detectChanges();
dynamicColumnDefFixture.detectChanges();
const dynamicColumnDefTable = dynamicColumnDefFixture.nativeElement.querySelector('cdk-table');
const dynamicColumnDefComp = dynamicColumnDefFixture.componentInstance;
// Add a new column and expect it to show up in the table
let columnA = 'columnA';
dynamicColumnDefComp.dynamicColumns.push(columnA);
dynamicColumnDefFixture.detectChanges();
expectTableToMatchContent(dynamicColumnDefTable, [
[columnA], // Header row
[columnA], // Data rows
[columnA],
[columnA],
]);
// Add another new column and expect it to show up in the table
let columnB = 'columnB';
dynamicColumnDefComp.dynamicColumns.push(columnB);
dynamicColumnDefFixture.detectChanges();
expectTableToMatchContent(dynamicColumnDefTable, [
[columnA, columnB], // Header row
[columnA, columnB], // Data rows
[columnA, columnB],
[columnA, columnB],
]);
// Remove column A expect only column B to be rendered
dynamicColumnDefComp.dynamicColumns.shift();
dynamicColumnDefFixture.detectChanges();
expectTableToMatchContent(dynamicColumnDefTable, [
[columnB], // Header row
[columnB], // Data rows
[columnB],
[columnB],
]);
});
it('should re-render the rows when the data changes', () => {
dataSource.addData();
fixture.detectChanges();
expect(getRows(tableElement).length).toBe(dataSource.data.length);
// Check that the number of cells is correct
getRows(tableElement).forEach(row => {
expect(getCells(row).length).toBe(component.columnsToRender.length);
});
});
it('should use differ to add/remove/move rows', () => {
// Each row receives an attribute 'initialIndex' the element's original place
getRows(tableElement).forEach((row: Element, index: number) => {
row.setAttribute('initialIndex', index.toString());
});
// Prove that the attributes match their indicies
const initialRows = getRows(tableElement);
expect(initialRows[0].getAttribute('initialIndex')).toBe('0');
expect(initialRows[1].getAttribute('initialIndex')).toBe('1');
expect(initialRows[2].getAttribute('initialIndex')).toBe('2');
// Swap first and second data in data array
const copiedData = component.dataSource!.data.slice();
const temp = copiedData[0];
copiedData[0] = copiedData[1];
copiedData[1] = temp;
// Remove the third element
copiedData.splice(2, 1);
// Add new data
component.dataSource!.data = copiedData;
component.dataSource!.addData();
// Expect that the first and second rows were swapped and that the last row is new
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe('1');
expect(changedRows[1].getAttribute('initialIndex')).toBe('0');
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
it('should clear the row view containers on destroy', () => {
const rowPlaceholder = fixture.componentInstance.table._rowPlaceholder.viewContainer;
const headerPlaceholder = fixture.componentInstance.table._headerRowPlaceholder.viewContainer;
spyOn(rowPlaceholder, 'clear').and.callThrough();
spyOn(headerPlaceholder, 'clear').and.callThrough();
fixture.destroy();
expect(rowPlaceholder.clear).toHaveBeenCalled();
expect(headerPlaceholder.clear).toHaveBeenCalled();
});
describe('with trackBy', () => {
let trackByComponent: TrackByCdkTableApp;
let trackByFixture: ComponentFixture<TrackByCdkTableApp>;
function createTestComponentWithTrackyByTable(trackByStrategy) {
trackByFixture = TestBed.createComponent(TrackByCdkTableApp);
trackByComponent = trackByFixture.componentInstance;
trackByComponent.trackByStrategy = trackByStrategy;
dataSource = trackByComponent.dataSource as FakeDataSource;
table = trackByComponent.table;
tableElement = trackByFixture.nativeElement.querySelector('cdk-table');
trackByFixture.detectChanges();
// Each row receives an attribute 'initialIndex' the element's original place
getRows(tableElement).forEach((row: Element, index: number) => {
row.setAttribute('initialIndex', index.toString());
});
// Prove that the attributes match their indicies
const initialRows = getRows(tableElement);
expect(initialRows[0].getAttribute('initialIndex')).toBe('0');
expect(initialRows[1].getAttribute('initialIndex')).toBe('1');
expect(initialRows[2].getAttribute('initialIndex')).toBe('2');
}
// Swap first two elements, remove the third, add new data
function mutateData() {
// Swap first and second data in data array
const copiedData = trackByComponent.dataSource.data.slice();
const temp = copiedData[0];
copiedData[0] = copiedData[1];
copiedData[1] = temp;
// Remove the third element
copiedData.splice(2, 1);
// Add new data
trackByComponent.dataSource.data = copiedData;
trackByComponent.dataSource.addData();
}
it('should add/remove/move rows with reference-based trackBy', () => {
createTestComponentWithTrackyByTable('reference');
mutateData();
// Expect that the first and second rows were swapped and that the last row is new
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe('1');
expect(changedRows[1].getAttribute('initialIndex')).toBe('0');
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
it('should add/remove/move rows with changed references without property-based trackBy', () => {
createTestComponentWithTrackyByTable('reference');
mutateData();
// Change each item reference to show that the trackby is not checking the item properties.
trackByComponent.dataSource.data = trackByComponent.dataSource.data
.map(item => { return {a: item.a, b: item.b, c: item.c}; });
// Expect that all the rows are considered new since their references are all different
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe(null);
expect(changedRows[1].getAttribute('initialIndex')).toBe(null);
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
it('should add/remove/move rows with changed references with property-based trackBy', () => {
createTestComponentWithTrackyByTable('propertyA');
mutateData();
// Change each item reference to show that the trackby is checking the item properties.
// Otherwise this would cause them all to be removed/added.
trackByComponent.dataSource.data = trackByComponent.dataSource.data
.map(item => { return {a: item.a, b: item.b, c: item.c}; });
// Expect that the first and second rows were swapped and that the last row is new
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe('1');
expect(changedRows[1].getAttribute('initialIndex')).toBe('0');
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
it('should add/remove/move rows with changed references with index-based trackBy', () => {
createTestComponentWithTrackyByTable('index');
mutateData();
// Change each item reference to show that the trackby is checking the index.
// Otherwise this would cause them all to be removed/added.
trackByComponent.dataSource.data = trackByComponent.dataSource.data
.map(item => { return {a: item.a, b: item.b, c: item.c}; });
// Expect first two to be the same since they were swapped but indicies are consistent.
// The third element was removed and caught by the table so it was removed before another
// item was added, so it is without an initial index.
const changedRows = getRows(tableElement);
expect(changedRows.length).toBe(3);
expect(changedRows[0].getAttribute('initialIndex')).toBe('0');
expect(changedRows[1].getAttribute('initialIndex')).toBe('1');
expect(changedRows[2].getAttribute('initialIndex')).toBe(null);
});
});
it('should match the right table content with dynamic data', () => {
const initialDataLength = dataSource.data.length;
expect(dataSource.data.length).toBe(3);
let data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
]);
// Add data to the table and recreate what the rendered output should be.
dataSource.addData();
expect(dataSource.data.length).toBe(initialDataLength + 1); // Make sure data was added
fixture.detectChanges();
data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
[data[3].a, data[3].b, data[3].c],
]);
});
it('should match the right table content with dynamic data source', () => {
const dynamicDataSourceFixture = TestBed.createComponent(DynamicDataSourceCdkTableApp);
component = dynamicDataSourceFixture.componentInstance;
tableElement = dynamicDataSourceFixture.nativeElement.querySelector('cdk-table');
dynamicDataSourceFixture.detectChanges();
// Expect that the component has no data source and the table element reflects empty data.
expect(component.dataSource).toBe(undefined);
expectTableToMatchContent(tableElement, [
['Column A']
]);
// Add a data source that has initialized data. Expect that the table shows this data.
const dynamicDataSource = new FakeDataSource();
component.dataSource = dynamicDataSource;
dynamicDataSourceFixture.detectChanges();
expect(dynamicDataSource.isConnected).toBe(true);
const data = component.dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A'],
[data[0].a],
[data[1].a],
[data[2].a],
]);
// Remove the data source and check to make sure the table is empty again.
component.dataSource = null;
dynamicDataSourceFixture.detectChanges();
// Expect that the old data source has been disconnected.
expect(dynamicDataSource.isConnected).toBe(false);
expectTableToMatchContent(tableElement, [
['Column A']
]);
// Reconnect a data source and check that the table is populated
const newDynamicDataSource = new FakeDataSource();
component.dataSource = newDynamicDataSource;
dynamicDataSourceFixture.detectChanges();
expect(newDynamicDataSource.isConnected).toBe(true);
const newData = component.dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A'],
[newData[0].a],
[newData[1].a],
[newData[2].a],
]);
});
it('should be able to apply classes to rows based on their context', () => {
const contextFixture = TestBed.createComponent(RowContextCdkTableApp);
const contextComponent = contextFixture.componentInstance;
tableElement = contextFixture.nativeElement.querySelector('cdk-table');
contextFixture.detectChanges();
let rowElements = contextFixture.nativeElement.querySelectorAll('cdk-row');
// Rows should not have any context classes
for (let i = 0; i < rowElements.length; i++) {
expect(rowElements[i].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-even')).toBe(false);
expect(rowElements[i].classList.contains('custom-row-class-odd')).toBe(false);
}
// Enable all the context classes
contextComponent.enableRowContextClasses = true;
contextFixture.detectChanges();
expect(rowElements[0].classList.contains('custom-row-class-first')).toBe(true);
expect(rowElements[0].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[0].classList.contains('custom-row-class-even')).toBe(true);
expect(rowElements[0].classList.contains('custom-row-class-odd')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-last')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-even')).toBe(false);
expect(rowElements[1].classList.contains('custom-row-class-odd')).toBe(true);
expect(rowElements[2].classList.contains('custom-row-class-first')).toBe(false);
expect(rowElements[2].classList.contains('custom-row-class-last')).toBe(true);
expect(rowElements[2].classList.contains('custom-row-class-even')).toBe(true);
expect(rowElements[2].classList.contains('custom-row-class-odd')).toBe(false);
});
it('should be able to apply classes to cells based on their row context', () => {
const contextFixture = TestBed.createComponent(RowContextCdkTableApp);
const contextComponent = contextFixture.componentInstance;
tableElement = contextFixture.nativeElement.querySelector('cdk-table');
contextFixture.detectChanges();
const rowElements = contextFixture.nativeElement.querySelectorAll('cdk-row');
for (let i = 0; i < rowElements.length; i++) {
// Cells should not have any context classes
const cellElements = rowElements[i].querySelectorAll('cdk-cell');
for (let j = 0; j < cellElements.length; j++) {
expect(cellElements[j].classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-even')).toBe(false);
expect(cellElements[j].classList.contains('custom-cell-class-odd')).toBe(false);
}
}
// Enable the context classes
contextComponent.enableCellContextClasses = true;
contextFixture.detectChanges();
let cellElement = rowElements[0].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(false);
cellElement = rowElements[1].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(true);
cellElement = rowElements[2].querySelectorAll('cdk-cell')[0];
expect(cellElement.classList.contains('custom-cell-class-first')).toBe(false);
expect(cellElement.classList.contains('custom-cell-class-last')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-even')).toBe(true);
expect(cellElement.classList.contains('custom-cell-class-odd')).toBe(false);
});
it('should be able to dynamically change the columns for header and rows', () => {
expect(dataSource.data.length).toBe(3);
let data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column A', 'Column B', 'Column C'],
[data[0].a, data[0].b, data[0].c],
[data[1].a, data[1].b, data[1].c],
[data[2].a, data[2].b, data[2].c],
]);
// Remove column_a and swap column_b/column_c.
component.columnsToRender = ['column_c', 'column_b'];
fixture.detectChanges();
let changedTableContent = [['Column C', 'Column B']];
dataSource.data.forEach(rowData => changedTableContent.push([rowData.c, rowData.b]));
data = dataSource.data;
expectTableToMatchContent(tableElement, [
['Column C', 'Column B'],
[data[0].c, data[0].b],
[data[1].c, data[1].b],
[data[2].c, data[2].b],
]);
});
});
interface TestData {
a: string;
b: string;
c: string;
}
class FakeDataSource extends DataSource<TestData> {
isConnected = false;
_dataChange = new BehaviorSubject<TestData[]>([]);
set data(data: TestData[]) { this._dataChange.next(data); }
get data() { return this._dataChange.getValue(); }
constructor() {
super();
for (let i = 0; i < 3; i++) { this.addData(); }
}
connect(collectionViewer: CollectionViewer): Observable<TestData[]> {
this.isConnected = true;
const streams = [this._dataChange, collectionViewer.viewChange];
return map.call(combineLatest(streams), ([data]) => data);
}
disconnect() {
this.isConnected = false;
}
addData() {
const nextIndex = this.data.length + 1;
let copiedData = this.data.slice();
copiedData.push({
a: `a_${nextIndex}`,
b: `b_${nextIndex}`,
c: `c_${nextIndex}`
});
this.data = copiedData;
}
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="column_b">
<cdk-header-cell *cdkHeaderCellDef> Column B</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.b}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="column_c">
<cdk-header-cell *cdkHeaderCellDef> Column C</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.c}}</cdk-cell>
</ng-container>
<cdk-header-row class="customHeaderRowClass"
*cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row class="customRowClass"
*cdkRowDef="let row; columns: columnsToRender"></cdk-row>
</cdk-table>
`
})
class SimpleCdkTableApp {
dataSource: FakeDataSource | null = new FakeDataSource();
columnsToRender = ['column_a', 'column_b', 'column_c'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: columnsToRender"></cdk-row>
</cdk-table>
`
})
class DynamicDataSourceCdkTableApp {
dataSource: FakeDataSource;
columnsToRender = ['column_a'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
}
@Component({
template: `
<cdk-table [dataSource]="dataSource" [trackBy]="trackBy">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="column_b">
<cdk-header-cell *cdkHeaderCellDef> Column B</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.b}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: columnsToRender"></cdk-row>
</cdk-table>
`
})
class TrackByCdkTableApp {
trackByStrategy: 'reference' | 'propertyA' | 'index' = 'reference';
dataSource: FakeDataSource = new FakeDataSource();
columnsToRender = ['column_a', 'column_b'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
trackBy = (index: number, item: TestData) => {
switch (this.trackByStrategy) {
case 'reference': return item;
case 'propertyA': return item.a;
case 'index': return index;
}
}
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container [cdkColumnDef]="column" *ngFor="let column of dynamicColumns">
<cdk-header-cell *cdkHeaderCellDef> {{column}} </cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{column}} </cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="dynamicColumns"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: dynamicColumns;"></cdk-row>
</cdk-table>
`
})
class DynamicColumnDefinitionsCdkTableApp {
dynamicColumns: any[] = [];
dataSource: FakeDataSource = new FakeDataSource();
@ViewChild(CdkTable) table: CdkTable<TestData>;
}
@Component({
template: `
<cdk-table [dataSource]="dataSource" role="treegrid">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: columnsToRender"></cdk-row>
</cdk-table>
`
})
class CustomRoleCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
columnsToRender = ['column_a'];
@ViewChild(CdkTable) table: CdkTable<TestData>;
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="['column_a']"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: ['column_a']"></cdk-row>
</cdk-table>
`
})
class DuplicateColumnDefNameCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_b">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row"> {{row.a}}</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="['column_a']"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: ['column_a']"></cdk-row>
</cdk-table>
`
})
class MissingColumnDefCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
}
@Component({
template: `
<cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="column_a">
<cdk-header-cell *cdkHeaderCellDef> Column A</cdk-header-cell>
<cdk-cell *cdkCellDef="let row; let first = first;
let last = last; let even = even; let odd = odd"
[ngClass]="{
'custom-cell-class-first': enableCellContextClasses && first,
'custom-cell-class-last': enableCellContextClasses && last,
'custom-cell-class-even': enableCellContextClasses && even,
'custom-cell-class-odd': enableCellContextClasses && odd
}">
{{row.a}}
</cdk-cell>
</ng-container>
<cdk-header-row *cdkHeaderRowDef="columnsToRender"></cdk-header-row>
<cdk-row *cdkRowDef="let row; columns: columnsToRender;
let first = first; let last = last; let even = even; let odd = odd"
[ngClass]="{
'custom-row-class-first': enableRowContextClasses && first,
'custom-row-class-last': enableRowContextClasses && last,
'custom-row-class-even': enableRowContextClasses && even,
'custom-row-class-odd': enableRowContextClasses && odd
}">
</cdk-row>
</cdk-table>
`
})
class RowContextCdkTableApp {
dataSource: FakeDataSource = new FakeDataSource();
columnsToRender = ['column_a'];
enableRowContextClasses = false;
enableCellContextClasses = false;
}
function getElements(element: Element, query: string): Element[] {
return [].slice.call(element.querySelectorAll(query));
}
function getHeaderRow(tableElement: Element): Element {
return tableElement.querySelector('.cdk-header-row')!;
}
function getRows(tableElement: Element): Element[] {
return getElements(tableElement, '.cdk-row');
}
function getCells(row: Element): Element[] {
return row ? getElements(row, '.cdk-cell') : [];
}
function getHeaderCells(tableElement: Element): Element[] {
return getElements(getHeaderRow(tableElement), '.cdk-header-cell');
}
function expectTableToMatchContent(tableElement: Element, expectedTableContent: any[]) {
const missedExpectations: string[] = [];
function checkCellContent(cell: Element, expectedTextContent: string) {
const actualTextContent = cell.textContent!.trim();
if (actualTextContent !== expectedTextContent) {
missedExpectations.push(
`Expected cell contents to be ${expectedTextContent} but was ${actualTextContent}`);
}
}
// Check header cells
const expectedHeaderContent = expectedTableContent.shift();
getHeaderCells(tableElement).forEach((cell, index) => {
const expected = expectedHeaderContent ?
expectedHeaderContent[index] :
null;
checkCellContent(cell, expected);
});
// Check data row cells
getRows(tableElement).forEach((row, rowIndex) => {
getCells(row).forEach((cell, cellIndex) => {
const expected = expectedTableContent.length ?
expectedTableContent[rowIndex][cellIndex] :
null;
checkCellContent(cell, expected);
});
});
if (missedExpectations.length) {
fail(missedExpectations.join('\n'));
}
}