Search code examples
htmlangulartypescriptangular-materialmat-card

Angular 8 display one image at a time


I am trying to display an avatar for each object that I have. The object is located in a MongoDB database and it is also displayed one by one. The problem that I have is that if I display the images as I display the objects (let's say I have 3 objects displayed), it shows all the 3 avatars for each object displayed, not just one image for each object. This is my code:

<ng-container *ngFor="let e of InstructorData">
            <mat-card class="example-card" *ngIf="e.slope === 'Sinaia'">
              <mat-card-header>
                <div mat-card-avatar class="margin" *ngFor="let avatar of imagesData1">
                  <img class="example-header-image" mat-card-image [src]="avatar" >
                </div>
                <mat-card-title>{{e.name}} {{e.surname}}</mat-card-title>
                <mat-card-subtitle>{{e.phoneNumber}}</mat-card-subtitle>
                <mat-card-subtitle>{{e.email}}</mat-card-subtitle>
              </mat-card-header>
              <mat-card-content>
                <p>{{e.description}}</p>
              </mat-card-content>
            </mat-card>
          </ng-container>


  imagesData1: any = [
    "./assets/img/ski1.jpg",
    "./assets/img/ski2.jpg",
    "./assets/img/ski3.jpg"
  ];

Solution

  • You need to modify your code to below you don't need to iterate over all the images just fetch the image according parent loop key it will always print single image

    <ng-container *ngFor="let e of InstructorData; let key = index">
            <mat-card class="example-card" *ngIf="e.slope === 'Sinaia'">
              <mat-card-header>
                <div mat-card-avatar class="margin">
                  <img class="example-header-image" mat-card-image [src]="imagesData1[key]" >
                </div>
                <mat-card-title>{{e.name}} {{e.surname}}</mat-card-title>
                <mat-card-subtitle>{{e.phoneNumber}}</mat-card-subtitle>
                <mat-card-subtitle>{{e.email}}</mat-card-subtitle>
              </mat-card-header>
              <mat-card-content>
                <p>{{e.description}}</p>
              </mat-card-content>
            </mat-card>
          </ng-container>