My component has an array of strings I want to display in a table. However, I want the table to have 4 columns per row. How can I use *ngFor to show 4 strings per row?
I'm aware there are solutions without using tables, but in this case I'm really interested in using a table.
Have to do a little transformation to the list of strings, its easy, just put the array through a function that makes and returns a new array to display
PLUNKR of my example below
my-comp.component.ts
items: any[] = ["item1","item2","item3","item4","item5","item6","item7","item8","item9"];
buildArr(theArr: String[]): String[][]{
var arrOfarr = [];
for(var i = 0; i < theArr.length ; i+=4) {
var row = [];
for(var x = 0; x < 4; x++) {
var value = theArr[i + x];
if (!value) {
break;
}
row.push(value);
}
arrOfarr.push(row);
}
return arrOfarr;
}
my-comp.component.html
<table id="myTable" class="table">
<thead>
<tr>
<th>Item1</th>
<th>Item2</th>
<th>Item3</th>
<th>Item4</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let row of buildArr(items)">
<td *ngFor="let item of row">{{item}}</td>
</tr>
</tbody>
</table>
You can transform your array of strings in an array of array of strings:
this.rowList = [];
var stringList = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3];
var colCount = 4;
for (var i = 0; i < stringList.length; i = i + 4) {
var element = stringList[i];
var row = [];
while (row.length < colCount) {
var value = stringList[i + row.length];
if (!value) {
break;
}
row.push(value);
}
this.rowList.push(row);
}
And then just use two ngFor:
<table>
<tbody>
<tr *ngFor="let row of rowList">
<td *ngFor="let col of row">{{col}}</td>
</tr>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With