From f1dff2f2e59d8f612d489501405b639dbabdc37e Mon Sep 17 00:00:00 2001 From: Andrew Seguin Date: Tue, 5 Sep 2017 16:53:26 -0700 Subject: [PATCH] fix(table): gracefully handle undefined/null columns --- src/cdk/table/row.ts | 4 ++-- src/cdk/table/table.spec.ts | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/cdk/table/row.ts b/src/cdk/table/row.ts index 1c521e64846e..320dd0fd48d0 100644 --- a/src/cdk/table/row.ts +++ b/src/cdk/table/row.ts @@ -42,8 +42,8 @@ export abstract class BaseRowDef { ngOnChanges(changes: SimpleChanges): void { // Create a new columns differ if one does not yet exist. Initialize it based on initial value - // of the columns property. - const columns = changes['columns'].currentValue; + // of the columns property or an empty array if none is provided. + const columns = changes['columns'].currentValue || []; if (!this._columnsDiffer && columns) { this._columnsDiffer = this._differs.find(columns).create(); this._columnsDiffer.diff(columns); diff --git a/src/cdk/table/table.spec.ts b/src/cdk/table/table.spec.ts index a07b92833488..548b1c794367 100644 --- a/src/cdk/table/table.spec.ts +++ b/src/cdk/table/table.spec.ts @@ -30,6 +30,7 @@ describe('CdkTable', () => { DuplicateColumnDefNameCdkTableApp, MissingColumnDefCdkTableApp, CrazyColumnNameCdkTableApp, + UndefinedColumnsCdkTableApp, ], }).compileComponents(); })); @@ -133,6 +134,21 @@ describe('CdkTable', () => { .toThrowError(getTableUnknownColumnError('column_a').message); }); + it('should not throw an error if columns are undefined on initialization', () => { + const undefinedColumnsFixture = TestBed.createComponent(UndefinedColumnsCdkTableApp); + undefinedColumnsFixture.detectChanges(); + + tableElement = undefinedColumnsFixture.nativeElement.querySelector('cdk-table'); + + expect(getHeaderRow(tableElement)).toBeNull('Should be no header without cells'); + + // Rows should be empty since there are no columns to display. + const rows = getRows(tableElement); + expect(rows[0].textContent).toBe(''); + expect(rows[1].textContent).toBe(''); + expect(rows[2].textContent).toBe(''); + }); + it('should be able to dynamically add/remove column definitions', () => { const dynamicColumnDefFixture = TestBed.createComponent(DynamicColumnDefinitionsCdkTableApp); dynamicColumnDefFixture.detectChanges(); @@ -753,6 +769,24 @@ class MissingColumnDefCdkTableApp { dataSource: FakeDataSource = new FakeDataSource(); } +@Component({ + template: ` + + + Column A + {{row.a}} + + + + + + ` +}) +class UndefinedColumnsCdkTableApp { + undefinedColumns; + dataSource: FakeDataSource = new FakeDataSource(); +} + @Component({ template: `