Home > Mobile >  Is there a way to know if an image has been loaded in the dom on Angular
Is there a way to know if an image has been loaded in the dom on Angular

Time:10-12

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

CodePudding user response:

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

  • Related