1

How would I display data from an array of arrays within Angular using *ngFor?

app.component.ts

list = {
    "one": [
      {
        "name": "a",
        "active": false
      },
      {
        "name": "b",
        "active": false
      }
    ],
    "two": [
      {
        "name": "c",
        "active": false
      },
      {
        "name": "d",
        "active": false
      }
    ]
  };

app.component.html

<div *ngFor="let item of list">
  <div *ngFor="let data of item">
    {{data.name}}
  </div>
<div>

The nesting of *ngFors doesn't appear to work in this case, but I cannot figure out why.

stackblitz

physicsboy
  • 5,656
  • 17
  • 70
  • 119

2 Answers2

3

use keyvalue pipe

Stackblitz Demo

<div *ngFor="let item of list | keyvalue">

  <div *ngFor="let data of item.value">
    {{data.name}}
  </div>
<div>

if you are using angular 5 and 6

<div *ngFor="let item of getListData">

  <div *ngFor="let data of list[item]">
    {{data.name}}
  </div>
</div>

get getListData(){
    return Object.keys(this.list)
}
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
  • Simply assuming that OP uses Angular 6.1 might be too optimistic. Furthermore, if he uses keyvalue pipe he probably should go with item.value instead of list[item.key] – Patrick Kelleter Aug 28 '18 at 18:09
  • yes you are right @PatrickKelleter – Krishna Rathore Aug 28 '18 at 18:14
  • Ah, amazing! Thanks for both solutions @KrishnaRathore. I was going to ask about the 6.1 solution as I was getting errors with it, but the legacy solution worked great. – physicsboy Aug 28 '18 at 18:58
2

Your outer "list" is no list at all. It is an object. Since objects are not strictly ordered by spec, they are not iteratable by Angular's ngFor.

However, with Angular 6.1 a new pipe was introduced, which actually makes objects iteratable as well, namely the KeyValue pipe.

So if you are using Angular 6.1 you may use that. Otherwise you will have to implement such a pipe on your own or prepare your data in your controller accordingly.

http://www.talkingdotnet.com/angular-6-1-introduces-new-keyvalue-pipe/

Patrick Kelleter
  • 2,631
  • 1
  • 13
  • 19