gpt4 book ai didi

javascript - 使用 ngFor 遍历二维数组

转载 作者:行者123 更新时间:2023-11-28 05:16:31 24 4
gpt4 key购买 nike

在这个问题上我一直在用头撞墙,但我终于感觉很亲近了。我想做的是读取我的测试数据,该数据进入二维数组,并将其内容打印到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com