簡體   English   中英

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中的一組對象。 聯系人中有九個對象,但為簡單起見,我僅在此處放置了兩個。

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)文件的contacts對象中使用9的名稱和圖像i?

您不必傳遞索引,只需使用變量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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM