How to loop with *ngFor in array of objects?

≡放荡痞女 提交于 2021-02-19 08:42:30

问题


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:


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>



回答2:


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




回答3:


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>



回答4:


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" id="{{'imgSlideContainer_'+i}}">
     <div>
        <img src="{{entry.getImageData()}}" id="{{'imgSlide_'+i}}" (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.



来源:https://stackoverflow.com/questions/42400154/how-to-loop-with-ngfor-in-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!