0
votes

I have an event listener issue with angular universal.

I have a document-page-component which contains a method that is called on an image load:

<img src="{{pageImage}}" class="{{module.class}}" alt="{{module.alt}}" (load)="calculateImageSize()" #img>

Here is the component method, calculating dynamically the width and height of the image, and updating a property.

  calculateImageSize() {
    // Get naturalWidth and naturalHeight of the signature
    this.imgWidth = this.img.nativeElement.naturalWidth;
    this.imgHeight = this.img.nativeElement.naturalHeight;

    // Change pageReady value to display the signatures
    this.pageReady = true;
  }

I have to do it this way because I don't know the size of the picture in advance, and I have to use this value to position elements on the page with those values.

The code works this way with a front-end Angular app, but the (load) is never called in Angular Universal mode.

I tried another implementation of the onload, directly inside the component, this way:

  ngAfterViewChecked() {
    this.renderer.listen(this.img.nativeElement, 'load', () => {
      this.calculateImageSize();
    })
  }

Angular universal does not support it as well...

Do you have any idea of alternative to onload listener that would work for Angular Universal.

A couple way to fix the issue that I think of are: - To make the call of the image in a service, convert it to base64, and pass it to the image as source. - Create an image element and inject it on the page.

I would prefer an alternative to the onload event listener though, so if anyone has an idea, feel free to tip in! Or to build an image and

1

1 Answers

1
votes

AFAIK at the present state of the Universal module getting the element's width and height is impossible. This is because there isn't any actual UI rendering that take place, hence the values naturalWidth, naturalHeight aren't populated.

I would suggest you to provide at least estimated dummy width/height for the images for server-side rendering. You can use isPlatformBrowser to sidetrack to different logic for browser and server.