javascripthtmlangular

How to loop with *ngFor in array of objects?


I'm learning Angular2, so please forgive me if I'm asking a stupid question. I am receiving an arrays of objects and it looks like this:

obj.json

data: [
        {
           item: "banana"
        }
     ],
     [
        {
           item: "apple"
        }
     ],
     [
        {
           item: "lemon"
        }
     ]

In my component file I have managed to scope it in a scope:

this.fruits = data[0].item;

The issue is I only manage to scope the first item, or the second item and so on, by the index. How can I scope them all and then show them in a HTML file with *ngFor?


Solution

  • Your array isn't valid JavaScript. Assuming your data actually looks like this:

    data: [
            {
               item: "banana"
            },
            {
               item: "apple"
            },
            {
               item: "lemon"
            }
         ]
    

    Then you'll iterate through the data like this:

    <li *ngFor="let fruit of data">
       <b> {{fruit.item}} </b>           
    </li>