3

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?

2
  • 1
    The full and exact error message would be quite helpful Commented Mar 17, 2018 at 19:16
  • 1
    Should be i.name, i.image etc not contacts[i]. i is an object of type contact not and index Commented Mar 17, 2018 at 19:17

1 Answer 1

9

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.