Reed
Reed

Reputation: 1642

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?

Upvotes: 0

Views: 3515

Answers (1)

Nitheesh
Nitheesh

Reputation: 19986

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.

Upvotes: 1

Related Questions