javascript - 使用 ngFor 遍历二维数组

标签 javascript html arrays angular typescript

在这个问题上我一直在用头撞墙,但我终于感觉很亲近了。我想做的是读取我的测试数据,该数据进入二维数组,并将其内容打印到 html 中的表格中,但我无法弄清楚如何使用 ngfor 循环遍历该数据集

这是我的 typescript 文件

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
    selector: 'fetchdata',
    template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
    public tableData: any[][];

    constructor(http: Http) {

        http.get('/api/SampleData/DatatableData').subscribe(result => {
            //This is test data only, could dynamically change
            var arr = [
                { ID: 1, Name: "foo", Email: "foo@foo.com" },
                { ID: 2, Name: "bar", Email: "bar@bar.com" },
                { ID: 3, Name: "bar", Email: "bar@bar.com" }
            ]
            var res = arr.map(function (obj) {
                return Object.keys(obj).map(function (key) {
                    return obj[key];
                });
            });

            this.tableData = res;
            console.log("Table Data")
            console.log(this.tableData)
        });
    }
}

这是我的 html,目前无法使用

<p *ngIf="!tableData"><em>Loading...</em></p>

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td>
            {{ tableData[data][i] }}
            </td>

        </tr>
    </tbody>
</table>

这是我的 console.log(this.tableData) 的输出 enter image description here

我的目标是在表格中采用这样的格式

1 | foo | bar@foo.com
2 | bar | foo@bar.com

我最好不要使用模型或接口(interface),因为数据是动态的,它随时可能发生变化。有谁知道如何使用 ngfor 循环遍历二维数组并将其内容打印到表中?

最佳答案

Marco Luzzara说,你必须为嵌套数组使用另一个 *ngFor。

我回答这个只是为了给你一个代码示例:

<table class='table' *ngIf="tableData">
    <tbody>
        <tr *ngFor="let data of tableData; let i = index">
            <td *ngFor="let cell of data">
              {{ cell }}
            </td>
        </tr>
    </tbody>
</table>

关于javascript - 使用 ngFor 遍历二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44978183/

相关文章:

javascript - ko.mapping observableArray 始终触发订阅

jquery - 视频帧作为海报

php - 更改在 PHP 中作为数组的类变量

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?

javascript - 如何停止缩略图上的无限 slider ?

javascript - 使用 websockets 的 Web 应用程序 “Could not establish connection. Receiving end does not exist."

javascript - 如何查看字段在 mongodb 中按字母顺序变化的时间?

html - 如何在调整高度时保持 100% 宽度的 CTA 图片不被拉伸(stretch)?

javascript - 如何动态创建嵌套元素?

php - 在php中获取包含月份开始日期和结束日期的每月数组