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.

3
  • 1
    You may want to look at the (load) event Commented Jun 28, 2019 at 19:18
  • @yurzui onload ? Commented Jun 28, 2019 at 19:24
  • Does this answer your question? Detect when image has loaded in img tag Commented Apr 17, 2022 at 18:41

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

7 Comments

There is no "loaded" event and that is why you have to create a directive? Excuse me, I'm starting with angular.
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
If you're sure that there is no caching for image then simply use (load)="do smth" instead of creating directive and using (loaded)="..."
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.
Firstly, this code does almost the same as js implementation stackoverflow.com/questions/280049/… with only one difference: I don't check for errors
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.