【问题标题】:Angular 4. How to print 2d array using html/typescript?Angular 4. 如何使用 html/typescript 打印二维数组?
【发布时间】:2017-10-05 07:17:51
【问题描述】:

我知道使用 Angular 4 项目打印常规数组,本网站上的 html 代码如下所示: https://angular.io/docs/ts/latest/guide/displaying-data.html

但是,我对如何使用 2d 数组执行此操作有点茫然。请帮忙。

【问题讨论】:

  • 使用嵌套循环

标签: html angular typescript multidimensional-array


【解决方案1】:

继续 Mike 的回答。

根据您实现二维数组的方式/您的意图,您也可以这样做:

// Declare a two dimensional array
public data: any[][] = [];

// Checks to see if the array contains the element, if it does then add it, otherwise initialise a new element and then assign the object to it.
    if (!this.data['item']) {
      this.data['item'] = [];
      this.data['item']['sub-item'] = {date: '2019-01-01', value: 0};
    } else {
      this.data['item']['sub-item'] = {date: '2019-01-01', value: 0};
    }

在 html 模板中,您可以通过键值管道使用嵌套 for 循环来遍历键值和值:

  <div *ngFor="let i of data| keyvalue">
    {{i.key}}
    <ng-container *ngFor="let j of i.value | keyvalue">
          {{j.value.date}}
          {{j.value.value}}
        </ng-container>
  </div>

结果将是:

2019-01-01 0

【讨论】:

    【解决方案2】:

    取决于您要做什么,但这里是一个基本示例。

    假设您在组件中定义了一个变量:

    public items: any[][];
    
    constructor() {
        this.items = [
            [1, 2], 
            [3, 4],
            [5, 6]
        ];
    }
    

    然后在你的模板中你可以使用嵌套的*ngFor:

    <div *ngFor="let i of items">
        <span *ngFor="let j of i">
            {{j}}
        </span>
    </div>
    

    输出:

    1 2
    3 4
    5 6
    

    根据您的用例调整它。

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2021-12-11
      相关资源
      最近更新 更多