【发布时间】:2017-12-12 04:32:21
【问题描述】:
我一直在用头撞墙有一段时间了,但我终于感觉很接近了。我想要做的是读取我的测试数据,它进入一个二维数组,并将其内容打印到 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>
这是我的console.log(this.tableData) 的输出
我的目标是让它在表格中像这样格式化
1 | foo | bar@foo.com
2 | bar | foo@bar.com
我最好不要使用模型或接口,因为数据是动态的,它随时可能发生变化。有谁知道如何使用 ngfor 循环遍历二维数组并将其内容打印到表格中?
【问题讨论】:
-
您可以简单地使用内部
*ngFor="let d of data"。index是计数器,指定循环执行的次数。
标签: javascript html arrays angular typescript