Skip to content

Commit 36dc1cf

Browse files
committed
fix(table): better handling of invalid data
The table data source is set up to expect an array and will throw a cryptic error down the line if the value is anything different. While typings should be enough to enforce this, if the value comes from somewhere in the view it may not get caught. Since the effort for handling it on our end is minimal, these changes add some logic that fall back to an empty array if the value is invalid. Fixes #18859.
1 parent 29e74eb commit 36dc1cf

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/material/table/table-data-source.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export class MatTableDataSource<T> extends DataSource<T> {
6969

7070
/** Array of data that should be rendered by the table, where each object represents one row. */
7171
get data() { return this._data.value; }
72-
set data(data: T[]) { this._data.next(data); }
72+
set data(data: T[]) { this._data.next(Array.isArray(data) ? data : []); }
7373

7474
/**
7575
* Filter term that should be used to filter out objects from the data array. To override how

src/material/table/table.spec.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,45 @@ describe('MatTable', () => {
213213
]);
214214
});
215215

216+
it('should fall back to empty table if invalid data is passed in', () => {
217+
component.underlyingDataSource.addData();
218+
fixture.detectChanges();
219+
expectTableToMatchContent(tableElement, [
220+
['Column A', 'Column B', 'Column C'],
221+
['a_1', 'b_1', 'c_1'],
222+
['a_2', 'b_2', 'c_2'],
223+
['a_3', 'b_3', 'c_3'],
224+
['a_4', 'b_4', 'c_4'],
225+
['Footer A', 'Footer B', 'Footer C'],
226+
]);
227+
228+
dataSource.data = null!;
229+
fixture.detectChanges();
230+
expectTableToMatchContent(tableElement, [
231+
['Column A', 'Column B', 'Column C'],
232+
['Footer A', 'Footer B', 'Footer C'],
233+
]);
234+
235+
component.underlyingDataSource.addData();
236+
fixture.detectChanges();
237+
expectTableToMatchContent(tableElement, [
238+
['Column A', 'Column B', 'Column C'],
239+
['a_1', 'b_1', 'c_1'],
240+
['a_2', 'b_2', 'c_2'],
241+
['a_3', 'b_3', 'c_3'],
242+
['a_4', 'b_4', 'c_4'],
243+
['a_5', 'b_5', 'c_5'],
244+
['Footer A', 'Footer B', 'Footer C'],
245+
]);
246+
247+
dataSource.data = {} as any;
248+
fixture.detectChanges();
249+
expectTableToMatchContent(tableElement, [
250+
['Column A', 'Column B', 'Column C'],
251+
['Footer A', 'Footer B', 'Footer C'],
252+
]);
253+
});
254+
216255
it('should update the page index when switching to a smaller data set from a page',
217256
fakeAsync(() => {
218257
// Add 20 rows so we can switch pages.

0 commit comments

Comments
 (0)