Angular2: ng for multiple objects in a row in a table

My component has an array of rows that I want to display in a table. However, I want the table to have 4 columns per row. How can I use * ngFor to display 4 lines per line?

I know that there are solutions without using tables, but in this case, I'm really interested in using a table.

+4
source share
3 answers

You need to convert the list of strings a bit, just, just put the array through a function that creates and returns a new array for 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>
+7
source

:

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);
}

ngFor:

<table>
    <tbody>
        <tr *ngFor="let row of rowList">
            <td *ngFor="let col of row">{{col}}</td>
        </tr>
    </tbody>
</table>
+2
<table>
<thead>
   <th>..</th>
<th>..</th>
<th>..</th>
<th>..</th>
</thead>
<tbody>
<tr ng-repeat="for component in components | groupBy: 3">
Data here
</tr>
</tbody>
</table>

This will require an angular filter / library. I did a similar thing for Sorting Elements in AngularJS for nested ng-repeat .

0
source

Source: https://habr.com/ru/post/1657418/


All Articles