user9159857
user9159857

Reputation:

Angular 4 ngFor looping through array of objects with HTML

I'm using Angular 4 and I want to loop through an array of objects and display the information in Angular Material grids tiles. My html (app.component.html) looks a bit like this

<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>

And contacts is an array of objects inside app.component.ts. There are NINE objects within contacts but for simplicity I've only put two here.

export class AppComponent {
// array of contact objects
contacts = [
{
  name: "Robbie Peck",
  image: "src/assets/robbie.jpg",
}, 
{
  name: "Jenny Sweets",
  image: "src/assets/jenny.jpg",
}, 

...

]
}

So rather than have nine different 's appear, each with their own information (looping i through contacts), I only have one and the console shows an error where it doesn't recognize contacts[i]. What have I done wrong? How can I get the to have 9 's, each with name and image i within the contacts object in the typescript (app.component.ts) file?

Upvotes: 3

Views: 20659

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

You don't have to pass the index, you can just use the variable i and access i.image and 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>

Upvotes: 9

Related Questions