0

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"
  ];
Anca Vulc
  • 145
  • 1
  • 10
  • just dont use ngfor if you dont want to iterate. use imagesData1[0] to get the first one – Elias Soares Jun 26 '20 at 14:52
  • I need different images, like one by one, for each object. And I only have one mat-card to iterate all the objects from the database. – Anca Vulc Jun 26 '20 at 14:56
  • You could use rxjs to display your images one after the other in rotation. Something like `image$ = timer(0, 5000).pipe(map(i => imagesData[i % imagesData1.length]))` in your component and use `` in your template? – Askirkela Jun 26 '20 at 15:01
  • Tried is now, is showing only the first image. – Anca Vulc Jun 26 '20 at 15:06
  • This is my last resort for adding images for the objects, as I couldn't do it through the database for my project. It was too complicated for what I knew. – Anca Vulc Jun 26 '20 at 15:08

1 Answers1

1

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>
Anku Singh
  • 914
  • 6
  • 12