From cfb83a0ebced5f9f9c2e97fc46505ec1115c13ca Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Tue, 11 Sep 2018 19:58:08 +0200 Subject: [PATCH] fix(grid-list): better handling of negative columns (#12939) Currently if, by any chance, assigns a negative number to the `cols` of a grid list, they'll get a cryptic error like `Invalid array length`, because down-the-line we use that number to create an array. These changes ensure that the value is always a positive number. --- src/lib/grid-list/grid-list.spec.ts | 22 +++++++++++++++++++++- src/lib/grid-list/grid-list.ts | 4 +++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/lib/grid-list/grid-list.spec.ts b/src/lib/grid-list/grid-list.spec.ts index aced2497031b..c97182ea15e8 100644 --- a/src/lib/grid-list/grid-list.spec.ts +++ b/src/lib/grid-list/grid-list.spec.ts @@ -1,5 +1,5 @@ import {TestBed, ComponentFixture} from '@angular/core/testing'; -import {Component, DebugElement, Type} from '@angular/core'; +import {Component, DebugElement, Type, ViewChild} from '@angular/core'; import {By} from '@angular/platform-browser'; import {MatGridList, MatGridListModule} from './index'; import {MatGridTile, MatGridTileText} from './grid-tile'; @@ -34,6 +34,20 @@ describe('MatGridList', () => { expect(() => fixture.detectChanges()).toThrowError(/tile with colspan 5 is wider than grid/); }); + it('should set the columns to zero if a negative number is passed in', () => { + const fixture = createComponent(GridListWithDynamicCols); + fixture.detectChanges(); + + expect(fixture.componentInstance.gridList.cols).toBe(2); + + expect(() => { + fixture.componentInstance.cols = -2; + fixture.detectChanges(); + }).not.toThrow(); + + expect(fixture.componentInstance.gridList.cols).toBe(1); + }); + it('should default to 1:1 row height if undefined ', () => { const fixture = createComponent(GridListWithUnspecifiedRowHeight); fixture.detectChanges(); @@ -334,6 +348,12 @@ class GridListWithInvalidRowHeightRatio { } ''}) class GridListWithTooWideColspan { } +@Component({template: ''}) +class GridListWithDynamicCols { + @ViewChild(MatGridList) gridList: MatGridList; + cols = 2; +} + @Component({template: `
diff --git a/src/lib/grid-list/grid-list.ts b/src/lib/grid-list/grid-list.ts index 3a96cc0307c2..fcac60396582 100644 --- a/src/lib/grid-list/grid-list.ts +++ b/src/lib/grid-list/grid-list.ts @@ -70,7 +70,9 @@ export class MatGridList implements OnInit, AfterContentChecked { /** Amount of columns in the grid list. */ @Input() get cols(): number { return this._cols; } - set cols(value: number) { this._cols = Math.round(coerceNumberProperty(value)); } + set cols(value: number) { + this._cols = Math.max(1, Math.round(coerceNumberProperty(value))); + } /** Size of the grid list's gutter in pixels. */ @Input()