【问题标题】:Angular 4 ngFor looping through array of objects with HTMLAngular 4 ngFor使用HTML循环遍历对象数组
【发布时间】:2018-08-26 17:03:43
【问题描述】:

我正在使用 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 中的一个对象数组。联系人中有九个对象,但为简单起见,我在这里只放了两个。

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]。我做错了什么?如何在 typescript (app.component.ts) 文件中的联系人对象中获得 9 的名称和图像 i ?

【问题讨论】:

  • 完整而准确的错误信息会很有帮助
  • 应该是 i.name、i.image 等而不是联系人 [i]。 i 是 contact not 和 index 类型的对象

标签: arrays angular typescript for-loop ngfor


【解决方案1】:

你不必传递索引,你可以使用变量i并访问i.imagei.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>

【讨论】:

    猜你喜欢
    • 2018-07-02
    • 2018-06-17
    • 2017-06-12
    • 2020-09-23
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 2015-06-09
    相关资源
    最近更新 更多