Search code examples
angulartypescriptangular-materialimagelist

mdc-image-list with loop in the image src


I am trying to view a set of images. My objective is in the image src to implement a function that individually fetches the images from another API.

My problem is when I log the console I see a duplication of results. Does anyone know the source of the problem and how can I solve it?

I leave below the example of duplicating the results, in fact they should only appear 8.

Image

DEMO

HTML

<ul class="mdc-image-list mdc-image-list--masonry masonry-image-list">
  <li class="mdc-image-list__item"
      *ngFor="let image of data">
   <img class="mdc-image-list__image"
        [src]="getImage(image.src)">
  </li>
</ul>

.TS

getImage(url) {
    console.log(url);
    return url;
  }

Solution

  • Made my mind up about what the issue likely is. Per my comment, it's likely that the GetImage() method is being evaluated multiple times as part of Angular's update cycle.

    I would iterate over the data array when it is first filled, doing your own singular evaluation of getImage(), saving the result:

    public data: any[];
    
    public ngOnInit(): void {
      const data = this.service.getDataSomehow();
    
      data.forEach((img: any) => {
        this.data.push(this.getImage(img.src));
      });
    }
    

    Then your template just changes slightly to be:

    <ul class="mdc-image-list mdc-image-list--masonry masonry-image-list">
      <li class="mdc-image-list__item"
          *ngFor="let image of data">
       <img class="mdc-image-list__image"
            [src]="image">
      </li>
    </ul>
    

    I will note, however, that you should look into using the DomSanitizer for dealing with your resource URLs.