Angular2 - * ngFor /循环通过带有数组的json对象

时间:2017-04-04 18:34:47

标签: angular

想要遍历json对象

//Defined on component side :
jsonObj = {
    '1' : [ {"title" : "title1" , "desc" : "desc1" }],
    '2' : [ {"title" : "title2" , "desc" : "desc2" }],
    '3' : [ {"title" : "title3" , "desc" : "desc3" }],
    '4' : [ {"title" : "title4" , "desc" : "desc4" }],
    '5' : [ {"title" : "title5" , "desc" : "desc5" }]
}

仅在模板方上使用*ngFor , 并且在组件方面没有任何编码(功能)

只想打印每个titledesc

这可能吗?如是 ?怎么样?

1 个答案:

答案 0 :(得分:2)

很高兴找到Angular本身的最佳解决方案,提供管道循环JSON及其keyvalue

<div *ngFor='let item of jsonObj | keyvalue'>
   Key: {{item.key}}

    <div *ngFor='let obj of item.value'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>

<强> WORKIGN DEMO

以前:

  

组件方:

objectKeys = Object.keys;
  

模板方:

<div *ngFor='let key of objectKeys(jsonObj)'>
   Key: {{key}}

    <div *ngFor='let obj of jsonObj[key]'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>

<强> WORKING DEMO