我想遍历一个对象数组,这是在我的json文件中。
JSON
[
{
"name": "Mike",
"colors": [
{"name": "blue"},
{"name": "white"}
]
},
{
"name": "Phoebe",
"colors": [
{"name": "red"},
{"name": "yellow"}
]
}
]
HTML
<div *ngFor="let person of persons">
<p>{{person.name}}</p> <!-- this works fine-->
<p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
{{color.name}}
</p>
</div>
我无法访问一个人的颜色数组。我如何实现这一目标?
我已经查看了这些帖子,但他们的解决方案无法帮助我:
您的代码(您显示的部分)工作正常(请参阅下面链接的plunker)。
由于您的问题中没有显示的唯一方法是将Javascript对象分配给变量persons
,我建议您向其展示更多代码/搜索问题。
https://plnkr.co/edit/rj4K2sKHTHsVtdt4OWfC?p=preview
@Component({
selector: 'my-app',
template: `
<div>
<div *ngFor="let person of persons">
<p>{{person.name}}</p> <!-- this works fine-->
<p *ngFor="let color of person.colors"> <!--I want to list the colors of the person here-->
{{color.name}}
</p>
</div>
</div>
`,
})
export class App {
name:string;
constructor() {
}
persons = [
{
"name": "Mike",
"colors": [
{"name": "blue"},
{"name": "white"}
]
},
{
"name": "Phoebe",
"colors": [
{"name": "red"},
{"name": "yellow"}
]
}
];
}
对于Angular 6.1+,您可以使用默认管道keyvalue
(Do review also):
<ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
以前:正如你所说:
Angular2 - *ngFor / loop through json object with array,这对你无济于事
你没有任何需要,因为你的代码工作正常,请检查