Folky.H Folky.H - 5 months ago 50
Javascript Question

Display a Loading icon while images loads

I want to show a background image/loading spinner inside a

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?


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.

  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.


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...

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

  constructor(private el:ElementRef) {
    this.el = el.nativeElement; = "url(";

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

Updated plunker.