Javascript 如何在对象数组中使用 *ngFor 循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42400154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop with *ngFor in array of objects?
提问by tholo
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:
我正在学习 Angular2,所以如果我问了一个愚蠢的问题,请原谅我。我正在接收一个对象数组,它看起来像这样:
obj.json
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?
问题是我只能通过索引确定第一个项目或第二个项目的范围。我如何才能将它们全部范围化,然后将它们显示在 HTML 文件中*ngFor?
回答by Cobus Kruger
Your array isn't valid JavaScript. Assuming your data actually looks like this:
您的数组不是有效的 JavaScript。假设您的数据实际上是这样的:
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>
回答by kind user
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>
回答by Yoav Schniederman
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>
回答by Wep0n
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
我有一个对象数组:private receipts:receipt[]其中收据是一个包含一些相关数据的对象
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):
现在填充数组后,我只是像这样使用它(不要介意离子幻灯片,这也适用于 div):
<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)
这符合预期。对于表单,{{entry.imageData}}如果它是可访问的属性,您也可以使用(是的,我测试了这个)
Similarily for nested Objects you should be able to simply {{entry.someSubObject.someSubSubObject}}
同样,对于嵌套对象,您应该能够简单地 {{entry.someSubObject.someSubSubObject}}
Hope this helps.
希望这可以帮助。

