Angular2-* ngFor/通过数组遍历json对象 [英] Angular2 - *ngFor / loop through json object with array

查看:376
本文介绍了Angular2-* ngFor/通过数组遍历json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要遍历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 , 并且在组件方面没有任何编码(功能).

With *ngFor only on template side , And without any coding (function) on component side.

只想打印每个titledesc

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

推荐答案

从Angular本身找到最佳解决方案真是太好了,它提供了通过JSON及其keyvalue

So great to find the best solution from Angular itself provides pipe to loop through JSON , and its 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

这篇关于Angular2-* ngFor/通过数组遍历json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆