Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: ngFor multiple objects per row in table [duplicate]

Tags:

angular

ngfor

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.

like image 615
BigTuna99 Avatar asked Oct 11 '16 18:10

BigTuna99


2 Answers

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>
like image 101
Logan H Avatar answered Oct 28 '22 05:10

Logan H


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>
like image 39
Guilherme Meireles Avatar answered Oct 28 '22 06:10

Guilherme Meireles