Angular2:ngFor通过对象数组迭代
问题描述:
例如与此JSON:Angular2:ngFor通过对象数组迭代
{
"TableRows": [
{
"Name": "Lord of the Rnis",
"Length": "2:40"
}
],
"Category": "Fantasy"
}
这些类:
export interface IMovies{
Category: string;
TableRows: ITableRows[];
}
export interface ITableRows{
Name: string;
Length: string;
}
以下ngFor逻辑的伟大工程,但它不是我想要的循环:
<tr *ngFor="let row of rows">
<td>{{row.Category}}</td>
<td>{{row.TableRows[0].Name}}</td>
<td></td>
</tr>
这个逻辑不工作:
<tr *ngFor="let row of rows.TableRows">
<td>{{row.Name}}</td>
<td>{{row.Length}}<td>
</tr>
我在这里做错了什么?
答
在你的情况下,你的第一条语句将不起作用。
第一条语句
<tr *ngFor="let row of rows">
<td>{{row.Category}}</td>
<td>{{row.TableRows[0].Name}}</td>
<td></td>
</tr>
这不是工作,因为ngFor
在angular 2
类似于在angular 1
ng-repeat
。为了使ngFor
工作,循环条目必须是一个数组,在你的情况下,行是一个对象而不是数组,因此显然它不起作用。
在你的第二个声明
<tr *ngFor="let row of rows.TableRows">
<td>{{row.Name}}</td>
<td>{{row.Length}}<td>
</tr>
的循环项目rows.TableRows
是一个元素的数组,因此,将工作和将产生的输出
Lord of the Rnis 2:40
我希望这是你在找什么。
什么是行?一个数组还是Imovies?或者一个ITableRows数组? – Abiezer