简体   繁体   English

Angular2:ng用于遍历对象数组

[英]Angular2: ngFor iterating through object array

For example with this JSON: 例如,使用以下JSON:

{
  "TableRows": [
    {
      "Name": "Lord of the Rnis",
      "Length": "2:40"
    }
  ],
  "Category": "Fantasy"
}

Into these classes: 进入这些类:

export interface IMovies{
    Category: string;
    TableRows: ITableRows[];
}

export interface ITableRows{
    Name: string;
    Length: string;
}

The following ngFor logic works great, but it's not what I want to loop: 以下ngFor逻辑效果很好,但这不是我想要循环的内容:

<tr *ngFor="let row of rows">
    <td>{{row.Category}}</td>
    <td>{{row.TableRows[0].Name}}</td>
    <td></td>
</tr>

This logic does NOT work: 此逻辑不起作用:

<tr *ngFor="let row of rows.TableRows">
     <td>{{row.Name}}</td>
     <td>{{row.Length}}<td>
</tr>

What am I doing wrong here? 我在这里做错了什么?

In your case, your first statement will not be working. 就您而言,您的第一条陈述将无效。

The first statement 第一句话

<tr *ngFor="let row of rows">
    <td>{{row.Category}}</td>
    <td>{{row.TableRows[0].Name}}</td>
    <td></td>
</tr>

This is not working because ngFor in angular 2 is similar to that of ng-repeat in angular 1 . 这是不工作,因为ngForangular 2是类似于的ng-repeatangular 1 In order for your ngFor to work, the looping item must be an array, in your case rows is an object and not an array so clearly it won't work. 为了使ngFor正常工作,循环项必须是一个数组,在您的情况下,行是一个对象,而不是一个数组,因此显然它是行不通的。

In your second statement 在你的第二个陈述中

<tr *ngFor="let row of rows.TableRows">
     <td>{{row.Name}}</td>
     <td>{{row.Length}}<td>
</tr>

The looping item rows.TableRows is an array with one element, so that will work and will produce the output as 循环项rows.TableRows是一个只有一个元素的数组,因此可以正常工作并产生以下输出

Lord of the Rnis    2:40

I hope this is what you are looking for. 我希望这是您要寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM