display array of numbers in 5x5 table in angular

Viewed 777

I have an array of numbers with a length of 25 numbers. I want to display this array in a table but display it so that i would have no more than 5 rows and 5 columns to display all 25 numbers. I don't want to code out the table to be 25 cells but i was wondering if there is a dynamic way in which i could tell the table create this many rows and columns.

this is what i have:
numArray =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25];

Html:

<table>
    <tbody>
      <tr *ngFor="let num of numArray; let i=index">
        <td>{{numArray}}</td>
      </tr>
    </tbody>
  </table>

I know this will just display the whole array 25 times but how can i specify 5x5 table to show my numArray?

2 Answers

You can do it with two ngFor loops:

<table>
  <tbody>
    <tr *ngFor="let row of [0,1,2,3,4]">
      <td *ngFor="let col of [0,1,2,3,4]">
        {{ numArray[5 * row + col] }}
      </td>
    </tr>
  </tbody>
</table>

See this stackblitz for a demo.

Javascript:

numMatrix = [
  [1, 2, 3, 4, 5], 
  [6, 7, 8, 9, 10],
  [11, 12, 13, 14, 15],
  [16, 17, 18, 19, 20],
  [21, 22, 23, 24, 25]
];

HTML:

<table>
  <tbody>
    <tr *ngFor="let numArray of numMatrix">
      <td *ngFor="let num of numArray">
        {{num}}
      </td>
    </tr>
  </tbody>
</table>
Related