Angular 4 ngFor 使用 HTML 遍历对象数组
Angular 4 ngFor looping through array of objects with HTML
我正在使用 Angular 4,我想遍历对象数组并在 Angular Material 网格图块中显示信息。我的 html (app.component.html) 看起来有点像这样
<div class="list" *ngIf="listContacts == true">
<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts">
<mat-grid-tile>
<div class="card">
<img src={{contacts[i].image}} alt="picture">
<h2>{{contacts[i].name}}</h2>
</div>
</mat-grid-tile>
</mat-grid-list>
</div>
联系人是 app.component.ts 中的一个对象数组。联系人中有 9 个对象,但为简单起见,我在这里只放了两个。
export class AppComponent {
// array of contact objects
contacts = [
{
name: "Robbie Peck",
image: "src/assets/robbie.jpg",
},
{
name: "Jenny Sweets",
image: "src/assets/jenny.jpg",
},
...
]
}
因此,与其出现九个不同的,每个都有自己的信息(通过联系人循环 i),我只有一个,控制台显示错误,无法识别联系人 [i]。我做错了什么?我怎样才能在打字稿 (app.component.ts) 文件的联系人对象中获得 9 的名称和图像 i?
不用传索引,直接用变量i
访问i.image
[=即可19=] 和 i.name
<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts" >
<mat-grid-tile>
<div class="card">
<img src={{i.image}} alt="picture">
<h2>{{i.name}}</h2>
</div>
</mat-grid-tile>
我正在使用 Angular 4,我想遍历对象数组并在 Angular Material 网格图块中显示信息。我的 html (app.component.html) 看起来有点像这样
<div class="list" *ngIf="listContacts == true">
<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts">
<mat-grid-tile>
<div class="card">
<img src={{contacts[i].image}} alt="picture">
<h2>{{contacts[i].name}}</h2>
</div>
</mat-grid-tile>
</mat-grid-list>
</div>
联系人是 app.component.ts 中的一个对象数组。联系人中有 9 个对象,但为简单起见,我在这里只放了两个。
export class AppComponent {
// array of contact objects
contacts = [
{
name: "Robbie Peck",
image: "src/assets/robbie.jpg",
},
{
name: "Jenny Sweets",
image: "src/assets/jenny.jpg",
},
...
]
}
因此,与其出现九个不同的,每个都有自己的信息(通过联系人循环 i),我只有一个,控制台显示错误,无法识别联系人 [i]。我做错了什么?我怎样才能在打字稿 (app.component.ts) 文件的联系人对象中获得 9 的名称和图像 i?
不用传索引,直接用变量i
访问i.image
[=即可19=] 和 i.name
<mat-grid-list cols="3" rowHeight="2:1" *ngFor="let i of contacts" >
<mat-grid-tile>
<div class="card">
<img src={{i.image}} alt="picture">
<h2>{{i.name}}</h2>
</div>
</mat-grid-tile>