1

I'm actually working on Angular and I want to know if there is a way to know if an image has been loaded correctly in the dom. I trie using this.image.nativeElement.width but the width is sent before the image loading.

HTML

<img #image [src]="imagePath">

TS

@ViewChild('image', {static: true})
  image: ElementRef<HTMLImageElement>;

Bozhinovski
  • 2,496
  • 3
  • 20
  • 38
sahakho
  • 21
  • 5
  • What do you mean correctly? I believe the image would load normally if you gave it the correct `src`. – manjiro sano Oct 11 '22 at 13:00
  • 1
    AFAIK `img` tag has `onLoad()` and `onError()` handles. Use them. – Rafael Oct 11 '22 at 13:01
  • Thanks @Rafael but the onLoad method is called even if the image is not loaded correctly – sahakho Oct 11 '22 at 13:02
  • @manjirosano the src is a link, so there is some latency between the moment I get the width and when the image is loaded. Is there any workaround to handle this lazy loading. I want to get the width of the image only when It's loaded to avoid getting 0 – sahakho Oct 11 '22 at 13:03

1 Answers1

4

You can do it in two ways:

Using AfterViewInit and access the element

@ViewChild('image')
  public img: ElementRef;

  ngAfterViewInit() {
    const image: HTMLImageElement = this.img.nativeElement;

    image.onload = () => {
      console.log('image loaded');
    };
  }

Using (load) event

<img #image [src]="imagePath" (load)="functionAfterLoad()">

https://stackblitz.com/edit/rotate-image-bdqndf?file=app/app.component.ts

Bozhinovski
  • 2,496
  • 3
  • 20
  • 38