简体   繁体   中英

Angular2: ngFor iterating through object array

For example with this 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:

<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 . 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.

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

Lord of the Rnis    2:40

I hope this is what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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