Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Angular2 - *ngFor / loop through json object with array

Want to loop through json object

//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" }]
}

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

Want to print just each title and desc

Is this possible ? If Yes ? How ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


Previously :

Component side :

objectKeys = Object.keys;

Template side :

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

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

</div>

WORKING DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...