How to iterate through an Object attributes in Angular 2

有些话、适合烂在心里 提交于 2019-12-03 09:43:47

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]});
}

slight modification to @eg16's answer and it worked like a charm for me -

the generateArray function looks like this-

generateArray(obj){
    return Object.keys(obj).map((key)=>{ return {key:key, value:obj[key]}});
}

and the template -

<li *ngFor="let item of generateArray(data)">{{item.key}}: {{item.value}}</li>

Starting with version 6.1, a KeyValue Pipe is made available by Angular:

<li *ngFor="let item of (data | keyvalue)">{{item.key}}: {{item.value}}</li>

This makes previous workarounds using Object.keys references or own implementations thereof obsolete.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!