Search code examples
angulartypescriptviewchildangular-lifecycle-hooks

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


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


Solution

  • 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