Detect when image has loaded in img tag

Angular

Angular Problem Overview


I am using Angular 2 and I need to detect if an image has loaded in an image tag.

Is there an event for that?

Something like this :

<img [src]="imagesource" [loaded]="dosomething()">

Angular Solutions


Solution 1 - Angular

<img [src]="imagesource" (load)="dosomething()">

Solution 2 - Angular

Extending the first answer to examine the image that just loaded.

    <img [src]="imagesource" (load)="onImageLoad($event)">
    
      onImageLoad(evt) {
        if (evt && evt.target) {
          const width = evt.target.naturalWidth;
          const height = evt.target.naturalHeight;
          const portrait = height > width ? true : false;
          console.log(width, height, 'portrait: ', portrait);
        }
      }

However, I saw that chrome sends the event twice, with different sizes! I was able to detect the correct size from the event where evt.scrElement.x and y was zero. But this might not always be the case and I'm not sure why there are two events?

    onImageLoad(evt) {
        if (evt && evt.target) {
          const x = evt.srcElement.x;
          const y = evt.srcElement.y;
          if ((x === 0 ) && (y === 0)) {
            const width = evt.srcElement.width;
            const height = evt.srcElement.height;
            portrait = height > width ? true : false;
            console.log('Loaded: ', width, height, 'portrait: ', portrait);
          }
        }
     }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoormanView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularintotechoView Answer on Stackoverflow