Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to loop with *ngFor in array of objects?

Writer Emily Wong

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?

1

4 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>
4

Your object isn't valid. I've edited it.

To iterate over object properties, use:

<ul> <li *ngFor='let elem of data'>{{ elem.item }}</li>
</ul>

Working plunker

export class SomeClass { public name: String; constructor(_name: String){ this.name= _name; }
}
let fruits : Array<SomeClass>[new SomeClass("banana"),new SomeClass("apple"),new SomeClass("lemon")];
<li *ngFor="let fruit of fruits"> <b> {{fruit.name}} </b>
</li>

I don't exactly see the problem. I'm using this as well.

I have an array of objects: private receipts:receipt[] where receipt is an object that contains some relevant data

export class receipt { public imageData; private accountNo; private tripNo; private ticketType; //..getters/setters and other variables
}

Now after filling the array I simply use it like this (nevermind the ion-slides, this does work for divs as well):

<ion-slide *ngFor="let entry of receipts; let i = index"> <div> <img src="{{entry.getImageData()}}" (click)="openImageUtil(entry, 'imgSlide_'+i)"> ...
</ion-slide>

This behaves as expected. For form, you can also use {{entry.imageData}} if it's an accessible property (Yes, I tested this)

Similarily for nested Objects you should be able to simply {{entry.someSubObject.someSubSubObject}}

Hope this helps.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy