Blog>
Snippets

Nesting ngFor to Display a Matrix

Demonstrate nested ngFor directives to display a two-dimensional array as a matrix of elements in the template.
import { Component } from '@angular/core';

@Component({
  selector: 'app-matrix-display',
  template: `
    <table>
      <tr *ngFor="let row of matrix; let i = index">
        <td *ngFor="let value of row; let j = index">
          {{ value }}
        </td>
      </tr>
    </table>
  `
})
export class MatrixDisplayComponent {
  matrix: number[][] = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
  ];
}
This Angular component uses nested ngFor directives to render a two-dimensional array as a matrix in a table layout. Each row of the matrix is iterated by the first ngFor, and each cell in the row is iterated by the nested ngFor.