@@ -24,6 +24,7 @@ fdescribe('CdkTable', () => {
24
24
DynamicDataSourceCdkTableApp ,
25
25
CustomRoleCdkTableApp ,
26
26
TrackByCdkTableApp ,
27
+ DynamicColumnDefinitionsCdkTableApp ,
27
28
RowContextCdkTableApp ,
28
29
] ,
29
30
} ) . compileComponents ( ) ;
@@ -108,6 +109,16 @@ fdescribe('CdkTable', () => {
108
109
expect ( fixture . nativeElement . querySelector ( 'cdk-table' ) . getAttribute ( 'role' ) ) . toBe ( 'treegrid' ) ;
109
110
} ) ;
110
111
112
+ fit ( 'should be able to dynamically add/remove column definitions' , ( ) => {
113
+ const dynamicColumnDefFixture = TestBed . createComponent ( DynamicColumnDefinitionsCdkTableApp ) ;
114
+ dynamicColumnDefFixture . detectChanges ( ) ;
115
+
116
+ const dynamicColumnDefComp = dynamicColumnDefFixture . componentInstance ;
117
+ expect ( dynamicColumnDefComp . dynamicColumns . push ( 'columnA' ) ) ;
118
+
119
+ dynamicColumnDefFixture . detectChanges ( ) ;
120
+ } ) ;
121
+
111
122
it ( 'should re-render the rows when the data changes' , ( ) => {
112
123
dataSource . addData ( ) ;
113
124
fixture . detectChanges ( ) ;
@@ -574,34 +585,25 @@ class TrackByCdkTableApp {
574
585
@Component ( {
575
586
template : `
576
587
<cdk-table [dataSource]="dataSource">
577
- <ng-container [cdkColumnDef]="column.id " *ngFor="let column of dynamicColumnDefs ">
578
- <cdk-header-cell *cdkHeaderCellDef> {{column.headerText}} </cdk-header-cell>
579
- <cdk-cell *cdkCellDef="let row"> {{row[ column.property]}} </cdk-cell>
588
+ <ng-container [cdkColumnDef]="column" *ngFor="let column of dynamicColumns ">
589
+ <cdk-header-cell *cdkHeaderCellDef> {{column}} </cdk-header-cell>
590
+ <cdk-cell *cdkCellDef="let row"> {{column}} </cdk-cell>
580
591
</ng-container>
581
592
582
- <cdk-header-row *cdkHeaderRowDef="dynamicColumnIds "></cdk-header-row>
583
- <cdk-row *cdkRowDef="let row; columns: dynamicColumnIds ;"></cdk-row>
593
+ <cdk-header-row *cdkHeaderRowDef="dynamicColumns "></cdk-header-row>
594
+ <cdk-row *cdkRowDef="let row; columns: dynamicColumns ;"></cdk-row>
584
595
</cdk-table>
585
596
`
586
597
} )
587
598
class DynamicColumnDefinitionsCdkTableApp {
588
- dynamicColumnDefs : any [ ] = [ ] ;
589
- dynamicColumnIds : string [ ] = [ ] ;
599
+ dynamicColumns : any [ ] = [ ] ;
590
600
591
601
dataSource : FakeDataSource = new FakeDataSource ( ) ;
592
- columnsToRender = [ 'column_a' , 'column_b' ] ;
593
602
594
603
@ViewChild ( CdkTable ) table : CdkTable < TestData > ;
595
604
596
605
addDynamicColumnDef ( ) {
597
- const nextProperty = this . dynamicColumnDefs . length ;
598
- this . dynamicColumnDefs . push ( {
599
- id : nextProperty ,
600
- property : nextProperty ,
601
- headerText : nextProperty
602
- } ) ;
603
-
604
- this . dynamicColumnIds = this . dynamicColumnDefs . map ( columnDef => columnDef . id ) ;
606
+ this . dynamicColumns . push ( this . dynamicColumns . length ) ;
605
607
}
606
608
}
607
609
0 commit comments