How to load images before showing an Angular Website

Viewed 5870

I have been doing a website in Angular, and I need to load all images before showing it. I tried to find a way to make a preloader view that would be shown until all the images located in the /assets folder are loaded, but I could not find anything.

How can I do it properly in Angular?

1 Answers

I can give you 2 options to accomplish (Assuming that you have list of image urls):

First way

images = ["IMG_1_SRC","IMG_2_SRC"];
loaded = 0;

loadImages(){
  for(let i = 0; i < this.images.length; i++){
    let img = new Image();
    img.onload = () => {
      this.loaded();
    }
    img.src = this.images[i];
  }
}

loaded(){
  this.loaded++;
  if(this.images.length == this.loaded){
    //all images loaded
  }
}

Second way

images = ["IMG_1_SRC","IMG_2_SRC"];
loaded = 0;

<img hidden *ngFor="let img of images;" [src]="img" (load)="loaded()" />

loaded(){
  this.loaded++;
  if(this.images.length == this.loaded){
    //all images loaded
  }
}
Related