Angular2: ngFor multiple objects per row in table

BigTuna99 picture BigTuna99 · Oct 11, 2016 · Viewed 12.6k times · Source

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.

Answer

Logan H picture Logan H · Oct 11, 2016

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

Example

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>