使用ngFor遍历二维数组

3
我已经在这个问题上苦思冥想了一段时间,但最终感觉离成功很近了。我的目标是读取测试数据(存储为二维数组),并将其内容打印到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

最好不要使用模型或接口,因为数据是动态的,随时可能会发生变化。请问有人知道如何使用ngfor循环遍历二维数组并在表格中打印其内容吗?


2
你可以简单地使用内部 *ngFor=“let d of data”index 是计数器,指定了您的循环执行次数的频率。 - Marco Luzzara
1个回答

6

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接