5

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.

2
  • 1
    Please show some code that demonstrates what you try to accomplish. Commented Oct 11, 2016 at 19:00
  • I recommend you use a table component such as primengs. Gives you alot of flexibility primefaces.org/primeng/#/datatable Commented Oct 11, 2016 at 19:51

3 Answers 3

9

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

0
<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 angular-filter module/library. I had done a similar thing for Sorting elements in AngularJS for nested ng-repeat question.

1 Comment

It's Angular2 question, not AngularJs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.