we had the same issue here creating a list with the ability to switch between list style and grid style.
The best way to set up the grid style with bootstrap and angular 2 is to manipulate the input array to the needs of the grid row/col arrangement.
Create a two dimensional array of rows with the amount of cols you need.
This example shows a full dynamic version.
We hope this will help you...
Component code:
export class Component implements OnChanges {
@Input() items: any[] = [];
@Input() gridCols: number = 4; // The number of cols in grid
private gridItems: any[][];
private gridValidValues = [1, 2, 3, 4, 6, 12]; // divisible without remainder col count
private initGrid() {
this.gridCols = this.gridCols | 0; // cast to int
this.gridCols = this.gridCols || 1; // ensure min. one row
if(!this.gridValidValues.find(value => this.gridCols === value)) {
this.gridCols = 4; // correct invalid input to default col count
}
let addition = this.items.length % this.gridCols > 0 ? 1 : 0;
let rows = ((this.items.length / this.gridCols) | 0) + addition;
this.gridItems = [];
let index = 0;
for(var i = 0; i < rows; i++) {
let row: any[] = [];
for(var j = 0; j < this.gridCols && index < this.items.length; j++) {
row.push(this.items[index]);
index++;
}
this.gridItems.push(row);
}
}
ngOnChanges(changes: SimpleChanges): void {
let itemsChange: SimpleChange = changes["items"];
if(itemsChange) {
let previous: any[] = itemsChange.previousValue;
let current: any[] = itemsChange.currentValue;
if(previous.length != current.length) {
this.initGrid();
}
}
}
}
Template code:
<div class="row"
template="ngFor let row of gridItems">
<div bind-class="'col-md-' + (12 / gridCols)"
template="ngFor let item of row">
{{item.anyvalue}}
</div>
</div>