Skip to content

Commit

Permalink
fix(grid-list): better handling of negative columns (#12939)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
crisbeto authored and jelbourn committed Sep 11, 2018
1 parent e24f24a commit cfb83a0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
22 changes: 21 additions & 1 deletion src/lib/grid-list/grid-list.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -334,6 +348,12 @@ class GridListWithInvalidRowHeightRatio { }
'<mat-grid-list cols="4"><mat-grid-tile colspan="5"></mat-grid-tile></mat-grid-list>'})
class GridListWithTooWideColspan { }

@Component({template: '<mat-grid-list [cols]="cols"></mat-grid-list>'})
class GridListWithDynamicCols {
@ViewChild(MatGridList) gridList: MatGridList;
cols = 2;
}

@Component({template: `
<div style="width:200px">
<mat-grid-list cols="1">
Expand Down
4 changes: 3 additions & 1 deletion src/lib/grid-list/grid-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down

0 comments on commit cfb83a0

Please sign in to comment.