@@ -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 ( ) ;
@@ -587,34 +598,25 @@ class TrackByCdkTableApp {
587
598
@Component ( {
588
599
template : `
589
600
<cdk-table [dataSource]="dataSource">
590
- <ng-container [cdkColumnDef]="column.id " *ngFor="let column of dynamicColumnDefs ">
591
- <cdk-header-cell *cdkHeaderCellDef> {{column.headerText}} </cdk-header-cell>
592
- <cdk-cell *cdkCellDef="let row"> {{row[ column.property]}} </cdk-cell>
601
+ <ng-container [cdkColumnDef]="column" *ngFor="let column of dynamicColumns ">
602
+ <cdk-header-cell *cdkHeaderCellDef> {{column}} </cdk-header-cell>
603
+ <cdk-cell *cdkCellDef="let row"> {{column}} </cdk-cell>
593
604
</ng-container>
594
605
595
- <cdk-header-row *cdkHeaderRowDef="dynamicColumnIds "></cdk-header-row>
596
- <cdk-row *cdkRowDef="let row; columns: dynamicColumnIds ;"></cdk-row>
606
+ <cdk-header-row *cdkHeaderRowDef="dynamicColumns "></cdk-header-row>
607
+ <cdk-row *cdkRowDef="let row; columns: dynamicColumns ;"></cdk-row>
597
608
</cdk-table>
598
609
`
599
610
} )
600
611
class DynamicColumnDefinitionsCdkTableApp {
601
- dynamicColumnDefs : any [ ] = [ ] ;
602
- dynamicColumnIds : string [ ] = [ ] ;
612
+ dynamicColumns : any [ ] = [ ] ;
603
613
604
614
dataSource : FakeDataSource = new FakeDataSource ( ) ;
605
- columnsToRender = [ 'column_a' , 'column_b' ] ;
606
615
607
616
@ViewChild ( CdkTable ) table : CdkTable < TestData > ;
608
617
609
618
addDynamicColumnDef ( ) {
610
- const nextProperty = this . dynamicColumnDefs . length ;
611
- this . dynamicColumnDefs . push ( {
612
- id : nextProperty ,
613
- property : nextProperty ,
614
- headerText : nextProperty
615
- } ) ;
616
-
617
- this . dynamicColumnIds = this . dynamicColumnDefs . map ( columnDef => columnDef . id ) ;
619
+ this . dynamicColumns . push ( this . dynamicColumns . length ) ;
618
620
}
619
621
}
620
622
0 commit comments