Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a Loading icon while images loads

I want to show a background image/loading spinner inside a div that will load an image inside of it, the image will show once it's fully loaded doing something like this:

   <div style="background-image:url('imageThatWillAppearBeforeLoad')"></div>

Demo (In jQuery)

How can I have the same using Angular2/Ionic2?

like image 450
Folky.H Avatar asked Jul 22 '16 22:07

Folky.H


People also ask

How do I show loader when image is loading?

Step 1: We must first insert the image into the html code page. Either inserting one “div” and loading the image as a “background” using CSS. Step 2: Adding CSS to display the loader in a div. Step 3: We will add a fadeout effect using jQuery.


2 Answers

Create a component that shows the placeholder image until the requested image is loaded, and hides the requested image. Once the image is loaded, you hide the placeholder and show the image.

@Component({
  selector: 'image-loader',
  template: `<img *ngIf="!loaded" src="url-to-your-placeholder"/>
    <img [hidden]="!loaded" (load)="loaded = true" [src]="src"/>`
})
export class ImageLoader {
  @Input() src;
}

See it working in Plunker.

Update

Now that I understand the requirements better, here's a solution with background image. It's a little hacky, and I like the original one better...

@Directive({
  selector: '[imageLoader]'
})
export class ImageLoader {
  @Input() imageLoader;

  constructor(private el:ElementRef) {
    this.el = el.nativeElement;
    this.el.style.backgroundImage = "url(http://smallenvelop.com/demo/image-loading/spinner.gif)";
  }

  ngOnInit() {
    let image = new Image();
    image.addEventListener('load', () => {
      this.el.style.backgroundImage = `url(${this.imageLoader})`;
    });
    image.src = this.imageLoader;
  }
}

Updated plunker.

like image 177
Yaron Schwimmer Avatar answered Sep 30 '22 18:09

Yaron Schwimmer


Here is a copy of one of my posts

I finally solved that problem with CSS! When an image is loading in ionic 2, the ion-img tag doesn't have any class. However, when the image is finally loaded, the ion-img tag get the class "img-loaded".

Here is my solution :

  <ion-img [src]="img.src"></ion-img>
  <ion-spinner></ion-spinner>

And my CSS :

.img-loaded + ion-spinner {
  display:none;
}
like image 26
Dev Avatar answered Sep 30 '22 16:09

Dev