Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an Object attributes in Angular 2

Here's my object (It has n number of dynamic keys. I've only shown two in the example below)

let obj = { abc:["some text", "some more text"], xyz:["more text", "what do you think?", "I'm tired now"]  } 

Here's my attempt to loop throw the above and print all the values

 <div *ngFor='let item of obj ; let i = index;'>             <p *ngFor="let value of obj.i">{{value}}  </div> 

But the above doesn't appear to work. What am I doing wrong and what's the correct syntax?

like image 801
user6123723 Avatar asked Aug 20 '16 23:08

user6123723


People also ask

How do you loop through an list of objects in angular?

Iterate throw all keys, and push each one into the array you created. Then Put the property name as a value of another key inside each objects. Yup. Thats it.

Can we use ngFor for objects?

ngFor by default tracks list items using object identity.


1 Answers

You could do something like this:

<li *ngFor="let o of obj">    <p *ngFor="let objArrayElement of generateArray(o)"> {{objArrayElement}} </p> </li> 

where generateArray looks like:

generateArray(obj){    return Object.keys(obj).map((key)=>{ return obj[key]}); } 
like image 80
etrupja Avatar answered Sep 30 '22 20:09

etrupja