infodev
infodev

Reputation: 5235

Print object items inside *ngFor in Angular

I want to print object items dynamically

const data = {
    title1: {
      name: "real title",
      value: ""
    },
    title2: {
      name: "real title2",
      value: ""
    },
    title3: {
      name: "real title3",
      value: ""
    },
    title4: {
      name: "real title4",
      value: ""
    },
    title5: {
      name: "real title5",
      value: ""
    },
    title6: {
      name: "real title6",
      value: ""
    }
};

I would print a list of data.title[i].name.

First I get titles list in array so that I could loop on them.

const titlesList = Object.keys(this.data);

then in HTML

<div *ngFor="let title of titlesList">
   {{ data.title.name }}
</div>

What I would print like:

 - real title 
 - real title1
 - real title2
 - ...

The error that I get:

ERROR TypeError: Cannot read property 'name' of undefined

Upvotes: 1

Views: 1770

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68685

You need to access via [] notation because your property key is stored in the title range variable. [] will evaluate the expression inside it, get the value and try to find property with that value.

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

Or instead of Object.keys you can use Object.values (ES8)

titlesList = Object.values(this.data);

and in the markup

 <div *ngFor="let title of titlesList">
    {{ title.name }}
 </div>

Angular 6.1 provides a new KeyValue pipe. Using this you can just use

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

Upvotes: 4

Ren&#233; Winkler
Ren&#233; Winkler

Reputation: 7088

With the latest relase of Angular 6.1 you can do it with the keyvalue pipe.

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

Upvotes: 3

Related Questions