使用 *ngFor (Angular 4) 遍历 JSON 对象数组
Loop through array of JSON object with *ngFor (Angular 4)
我想遍历对象数组,它在我的 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
( ) :
<ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
以前 : 正如你所说的 :
,这帮不了你
你不需要那个,因为你的代码工作正常,请检查
我想遍历对象数组,它在我的 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
(
<ul>
<li *ngFor="let recipient of map | keyvalue">
{{recipient.key}} --> {{recipient.value}}
</li>
</ul>
以前 : 正如你所说的 :
你不需要那个,因为你的代码工作正常,请检查