Skip to content

Commit cfb83a0

Browse files
crisbetojelbourn
authored andcommitted
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.
1 parent e24f24a commit cfb83a0

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

src/lib/grid-list/grid-list.spec.ts

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {TestBed, ComponentFixture} from '@angular/core/testing';
2-
import {Component, DebugElement, Type} from '@angular/core';
2+
import {Component, DebugElement, Type, ViewChild} from '@angular/core';
33
import {By} from '@angular/platform-browser';
44
import {MatGridList, MatGridListModule} from './index';
55
import {MatGridTile, MatGridTileText} from './grid-tile';
@@ -34,6 +34,20 @@ describe('MatGridList', () => {
3434
expect(() => fixture.detectChanges()).toThrowError(/tile with colspan 5 is wider than grid/);
3535
});
3636

37+
it('should set the columns to zero if a negative number is passed in', () => {
38+
const fixture = createComponent(GridListWithDynamicCols);
39+
fixture.detectChanges();
40+
41+
expect(fixture.componentInstance.gridList.cols).toBe(2);
42+
43+
expect(() => {
44+
fixture.componentInstance.cols = -2;
45+
fixture.detectChanges();
46+
}).not.toThrow();
47+
48+
expect(fixture.componentInstance.gridList.cols).toBe(1);
49+
});
50+
3751
it('should default to 1:1 row height if undefined ', () => {
3852
const fixture = createComponent(GridListWithUnspecifiedRowHeight);
3953
fixture.detectChanges();
@@ -334,6 +348,12 @@ class GridListWithInvalidRowHeightRatio { }
334348
'<mat-grid-list cols="4"><mat-grid-tile colspan="5"></mat-grid-tile></mat-grid-list>'})
335349
class GridListWithTooWideColspan { }
336350

351+
@Component({template: '<mat-grid-list [cols]="cols"></mat-grid-list>'})
352+
class GridListWithDynamicCols {
353+
@ViewChild(MatGridList) gridList: MatGridList;
354+
cols = 2;
355+
}
356+
337357
@Component({template: `
338358
<div style="width:200px">
339359
<mat-grid-list cols="1">

src/lib/grid-list/grid-list.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ export class MatGridList implements OnInit, AfterContentChecked {
7070
/** Amount of columns in the grid list. */
7171
@Input()
7272
get cols(): number { return this._cols; }
73-
set cols(value: number) { this._cols = Math.round(coerceNumberProperty(value)); }
73+
set cols(value: number) {
74+
this._cols = Math.max(1, Math.round(coerceNumberProperty(value)));
75+
}
7476

7577
/** Size of the grid list's gutter in pixels. */
7678
@Input()

0 commit comments

Comments
 (0)