0

I would like to render table giving the array, e.g. let results=[[1,2,3],[4,5,6],[7,8,9]] looking like:

1 2 3
4 5 6
7 8 9

but have no idea how to set number of rows properly, using such a template

<table>
  <ng-container *ngFor="let result of results">
    <tr>
      <td>{{result}}</td>
    </tr>
  </ng-container>
</table>

I get the table with one row in fact. How to manage rows number for such a case? It may seems trivial but hard to manage due to lack of experience with Angular2+. Thank you!

Vala Khosravi
  • 2,352
  • 3
  • 22
  • 49
Dmitry Adonin
  • 1,064
  • 3
  • 16
  • 36

1 Answers1

2

For cases like this, I like to use a nested array and iterate on the top array as a <tr> element, and then iterating on that "row" to display the elements. Assuming you change your array to:

let results=[[1,2,3],[4,5,6],[7,8,9]]

Your view would be:

<table>
  <tr *ngFor="let row of results">
    <td *ngFor="let item of row">{{item}}</td>
  </tr>  
</table>

If you can't transform your array to a nested array, you can create a function to do that and call it in the template like:

<tr *ngFor="let row of transformToNestedArray(results, 3)">

And this function would be defined in your code as:

transformToNestedArray = (arr, cols) => {
  let newArray = [];
    while(arr.length){
      newArray.push(arr.splice(0, cols))
  }
  return newArray;
}

The result from that function will only be used in the view and will not modify your "results" variable.