Search code examples
htmlcssngfor

How to display array elements like a matrix using ngFor and table [Angular]


I'm creating a Month picker in Angular. I followed this, this and this also but cannot achieve what I want. I've months from Jan to Dec. I want to display them like a 4X3 matrix. But I'm getting all the months in a single column vertically. Or may be that I'm unnecessarily over complicating my code. Here is my code.

monthpikcer.component.html

<div class="my-table-div">
  <table class="my-table" *ngFor="let row of months">
    <tr class="month-row" *ngFor="let col of row">
      <td class="month-name">{{col}}</td>
    </tr>
  </table> 
</div>

monthpicker.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  ...
})
export class MonthpickerComponent implements OnInit {

  months = [
    ['Jan', 'Feb', 'Mar'],
    ['Apr', 'May', 'Jun'],
    ['Jul', 'Aug', 'Sep'],
    ['Oct', 'Nov', 'Dec']
  ];

  constructor() { }

  ngOnInit() {
  }
}

PS: I don't want to use bootstrap row and col. My code is not working. Please correct me.


Solution

  • you can use this
    
    <table class="my-table">
        <tr class="month-row" *ngFor="let row of months; index as i">       
                <table class="my-table">
                    <tr class="month-row"  >
                        <td *ngFor="let col of row" class="month-name">{{col}}</td>
                    </tr>
                </table>            
        </tr>
    </table>
    

    Output is

    <table>
    <tr><td>Jan</td><td>Feb</td><td>Mar</td></tr>
    <tr><td>Apr</td><td>may</td><td>Jun</td></tr>
    <tr><td>Jul</td><td>Aug</td><td>Sep</td></tr>
    <tr><td>Oct</td><td>Nov</td><td>Dec</td></tr>
    <table>