2

How could I do to know when an image has been fully loaded and then show it? Let me explain: I'm showing an image in the following way:

<img src = "www.domain.com">

but there are times it takes to load and I want to show it only when it is ready to show (100% loaded), as you might know when Is 100% loaded that image? and I would like to show a loading spinner while the loading of that image is complete, I am using angular 7.

msanford
  • 11,803
  • 11
  • 66
  • 93
JulianProg
  • 183
  • 1
  • 5
  • 16

1 Answers1

9

There is no difference in how you would check it in Angular or in js.

You need to check for img.complete flag or wait for image.onLoad event to be fired.

Angular directives allow us to handle such behaviors of element, so let's create a directive:

import { Directive, Output, EventEmitter, ElementRef, HostListener, OnInit } from '@angular/core';

@Directive({
  selector: 'img[loaded]'
})
export class LoadedDirective {

  @Output() loaded = new EventEmitter();

  @HostListener('load')
  onLoad() {
    this.loaded.emit();
  }

  constructor(private elRef: ElementRef<HTMLImageElement>) {
    if (this.elRef.nativeElement.complete) {
      this.loaded.emit();
    }
  }
}

Now you can catch when an image has been loaded by simple code:

<img src="..." alt="" (loaded)="do whatever you want here">

Ng-run Example

TmTron
  • 17,012
  • 10
  • 94
  • 142
yurzui
  • 205,937
  • 32
  • 433
  • 399
  • There is no "loaded" event and that is why you have to create a directive? Excuse me, I'm starting with angular. – JulianProg Jun 28 '19 at 20:24
  • There's `load` event but you have to check `complete` property because there can be a case when image is being loaded from cache so `(load)` event will never be fired – yurzui Jun 28 '19 at 20:26
  • If you're sure that there is no caching for image then simply use `(load)="do smth"` instead of creating directive and using `(loaded)="..."` – yurzui Jun 28 '19 at 20:27
  • ok I understand. Will there be a tutorial or a page where you can guide me and thus understand what you have done? since I do not understand the code because I'm just starting with angular. I did not want to copy and paste without understanding it. – JulianProg Jun 28 '19 at 20:31
  • Firstly, this code does almost the same as js implementation https://stackoverflow.com/questions/280049/how-to-create-a-javascript-callback-for-knowing-when-an-image-is-loaded with only one difference: I don't check for errors – yurzui Jun 28 '19 at 20:33
  • Any directive can define Output event and can use HostListener https://angular.io/api/core/HostListener to handle any native events such as click, mousemove, load etc – yurzui Jun 28 '19 at 20:34
  • We can inject ElementRef in any directive and will be refer to the host element https://angular.io/api/core/ElementRef – yurzui Jun 28 '19 at 20:35