问题描述
一段时间以来,我一直在头顶上撞墙,但我终于感觉很近了.我想做的是读取我的测试数据,该数据进入二维数组,并将其内容打印到html中的表中,但是我不知道如何使用ngfor遍历该数据集
I've been beating my head up against the wall on this one for a while but I finally feel close. What I'm trying to do is read my test data, which goes to a two dimensional array, and print its contents to a table in the html, but I can't figure out how to use an ngfor to loop though that dataset
这是我的打字稿文件
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
Here is my html which does not work at the moment
<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)
的输出
我的目标是在表格中将其格式化为这样
My goal is to have it formatted like this in the table
1 | foo | bar@foo.com
2 | bar | foo@bar.com
最好不要使用模型或接口,因为数据是动态的,它可能随时更改.有谁知道如何使用ngfor遍历二维数组并将其内容打印在表中?
Preferably I'd like to not use a model or an interface because the data is dynamic, it could change at any time. Does anyone know how to use the ngfor to loop through a two dimensional array and print its contents in the table?
推荐答案
像 Marco Luzzara 所说,你有为嵌套数组使用另一个* ngFor.
Like Marco Luzzara said, you have to use another *ngFor for the nested arrays.
我回答这个只是为了给您一个代码示例:
I answer this just to give you a code example:
<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>
这篇关于使用ngFor遍历二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!