首页 > 解决方案 > 如何使用 ngFor 和 table [Angular] 显示矩阵等数组元素

问题描述

我正在 Angular 中创建月份选择器。我遵循了这个这个这个,但也无法实现我想要的。我从一月到十二月有几个月的时间。我想像 4X3 矩阵一样显示它们。但是我将所有月份都放在一个垂直的列中。或者可能是我不必要地过度复杂化我的代码。这是我的代码。

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:我不想使用 bootstraprowcol. 我的代码不起作用。请纠正我。

标签: htmlcssngfor

解决方案


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>

输出是

<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>


推荐阅读