Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用ngFor遍历二维数组_Javascript_Html_Arrays_Angular_Typescript - Fatal编程技术网

Javascript 使用ngFor遍历二维数组

Javascript 使用ngFor遍历二维数组,javascript,html,arrays,angular,typescript,Javascript,Html,Arrays,Angular,Typescript,我已经在这件事上撞了好一阵子了,但我终于感觉很亲近了。我试图做的是读取我的测试数据,它进入一个二维数组,并将其内容打印到html中的一个表中,但我不知道如何使用ngfor循环该数据集 这是我的打字脚本文件 import { Component } from '@angular/core'; import { Http } from '@angular/http'; @Component({ selector: 'fetchdata', template: require('./

我已经在这件事上撞了好一阵子了,但我终于感觉很亲近了。我试图做的是读取我的测试数据,它进入一个二维数组,并将其内容打印到html中的一个表中,但我不知道如何使用ngfor循环该数据集

这是我的打字脚本文件

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>
最好不要使用模型或接口,因为数据是动态的,随时都可能发生变化。有人知道如何使用ngfor循环二维数组并在表中打印其内容吗?

如前所述,您必须使用另一个*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>

{{cell}}

您只需使用内部的
*ngFor=“let d of data”
index
是计数器,指定循环执行的次数。
<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>