Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
tholo Avatar asked Feb 22 '17 19:02

tholo


People also ask

Does ngFor work on objects?

The ngFor directive accepts any object that implements the Iterable interface. You can read more about iterators here. So, for example, we can create our own iterable and just give it to the ngFor directive. And it just works.

Why * is used in ngFor?

In *ngFor the * is a shorthand for using the new angular template syntax with a template tag, this is also called structural Directive.It is helpful to know that * is just a shorthand to explicitly defining the data bindings on a template tag.

How can I use two ngFor in one div?

You can't use multiple *ngFor s in the same element as those are structural directives and angular handles them in a specific way (basically for each structural directive it creates an ng-template element which then holds the directive itself, you can read more about it here: https://angular.io/guide/structural- ...

Is ngFor a loop?

One of the most basic and common is ngFor which is an implementation of a for loop . ngFor is designed to work with collections. Since we have a collection of events let's see how to use the ngFor directive in our code.


Video Answer


1 Answers

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>
like image 180
Cobus Kruger Avatar answered Sep 22 '22 23:09

Cobus Kruger