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
?
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.
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.
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- ...
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With