0

I´m fairly new to Angular2, and i want to read out a json file. It´s working, that I get the file from a REST-Client, i can save the file in a local variable in a component. Now I´m trying to read properties (Array) with ngFor, but this isn´t working. Here´s the html:

<div *ngFor="let categories of tasks.tasks">
    {{categories}} --> Display name of categorie (epg, recs)
    <p *ngFor="let task of categories">{{task.text}}</p>
</div>

And the JSON-File:

{
    "tasks": {
        "epg": [{
            "text": "\\\\...\\Daten\\Videos\\Aufnahmen"
        }, {
            "text": "C:\\Users\\...\\Desktop"
        }],
        "recs": [{
            "text": "\\\\...\\Daten\\Videos\\Aufnahmen"
        }, {
            "text": "C:\\...\\Junias\\Desktop"
        }]
    }
}

Hope someone can help me ;)

Junias
  • 3,037
  • 2
  • 15
  • 21
  • What does 'isnt working' mean? Does it show anything? Does it show nothing? – Alexander Ciesielski Oct 27 '16 at 09:10
  • The subtree `tasks` is not an array, so you can't loop through it with `ngFor`. – Maximilian Riegler Oct 27 '16 at 09:33
  • http://stackoverflow.com/questions/31490713/iterate-over-typescript-dictionary-in-angular-2 – Bazinga Oct 27 '16 at 10:57
  • Thanks for the comment, i changed the subtree tasks to an Array ;) But there´s still the question of how can i loop through both arrays... There stands `[object Object]` instead of "epg" or "recs". The question is, how can i get the value (name) of the "categorie" ? And how can i loop through both JSON-Arrays ;) – Junias Oct 28 '16 at 07:19

1 Answers1

0

Consider

z={
"tasks": {
    "epg": [{
        "text": "\\\\...\\Daten\\Videos\\Aufnahmen"
    }, {
        "text": "C:\\Users\\...\\Desktop"
    }],
    "recs": [{
        "text": "\\\\...\\Daten\\Videos\\Aufnahmen"
    }, {
        "text": "C:\\...\\Junias\\Desktop"
    }]
}

Modify your JSON as

  let a=this.z.tasks;
  this.z = Object.keys(a).map(function(k) { return a[k] });

Here is a plunker

Parshwa Shah
  • 331
  • 4
  • 14
  • Thank you very much! But this is a problem, because the tasks (epg, recs, ...) could be N tasks (epg, recs, timers, systems, ...). So I thought about a "double" ngFor... Do you also have a solution for this? Thanks ;) – Junias Oct 28 '16 at 04:57
  • This looks quite good. ;) But there is one more thing, which isn´t possible (i think so...) in this solution: I want to display the "key" of the the array, so the output should be: epg \\\\...\\Daten\\Videos\\Aufnahmen C:\\Users\\...\\Desktop recs \\\\...\\Daten\\Videos\\Aufnahmen C:\\Users\\...\\Desktop Do you understand what i mean? And it does´nt matter, if the json should be edited or the html ;) Thank you so much! – Junias Oct 28 '16 at 09:35