92

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()">

2 Answers 2

174
<img [src]="imagesource" (load)="dosomething()">
Sign up to request clarification or add additional context in comments.

14 Comments

Hi, do you know why Observable.fromEvent(elementReference, 'load') does not work the same way? Also, any hint on why dosomething() gets called more than once each time src changes? Thanks
I think that dosomething() is called twice is a Chrome issue. I investigated and commented on a similar question but don't remember details.
Ok thanks, and any experience on Observable.fromEvent(imgElementReference, 'load') vs <img (load)="...">?
I never tried Observable.fromEvent(elementReference, 'load'). How does it not work the same way?
@GünterZöchbauer Thanks, I got the cause, the image was within *ngIf whose condition was false. Sorry for bothering.
|
10

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

3 Comments

What is the difference between the load and and onload listeners?
Good question. I am not sure but I think that onload is the native html event, and load is the Angular template equivalent. See stackoverflow.com/questions/43301624/….
@Ben, in Angular the events you attach in the html tag are the same without on, e.g. (click) vs onclick, (keydown) vs onkeydown, etc. -see that in javascript not enclosed by ( ). When you use fromEvent rxjs operator, HostListener or addEventListener you always use the "not on" way. (the event name are click, keydown, load...)

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.