Home > Net >  Get dimensions of an image after render finishes, in Angular
Get dimensions of an image after render finishes, in Angular

Time:10-12

I am trying to get the rendered size of an image in a component. Using the (load) event, I am getting the size of the image as it is displayed at that moment (pic1) and the "final" size after the page fully renders. I guess I can use ngAfterViewChecked but that would mean I am constantly calculating that size when the only meaningful instance for that is when the window opens or resizes

(load) event fires

CodePudding user response:

  • An alternate approach that you can use is, subscribe to changes in Window: resize event using the HostListener in order to calculate image dimensions, as shown in the following code snippet.
import { HostListener } from '@angular/core';

@HostListener('window:resize', ['$event'])
  // Invoke function to compute the image dimensions here
}

Note: You can also invoke the function to compute the dimensions of the said image inside AfterViewInit lifecycle hook rather than on load event.

  • Another approach is to calculate image dimensions by listening to changes in the Window: resize event using the fromEvent, as shown in the code snippet below.
import { fromEvent } from 'rxjs';

changeSubscription$: Subscription

ngOnInit() {
  this.windowResizeEventChanges$ = fromEvent(window, 'resize').subscribe(event => {
    // Invoke function to compute the image dimensions here
  });
}

ngOnDestroy() {
  this.windowResizeEventChangesn$.unsubscribe() // Unsubscribe to stop listening the changes in Window: resize
}

Read more about fromEvent here.

CodePudding user response:

I ended up using a Mutation Observer, watching for attribute changes, attached to the item that contains the image. In my case there is a need for some management because it doesn't just run once, but it solves the issue

ngAfterViewInit() {
  this.refElement = this.appsContainer.nativeElement.querySelector('item') as HTMLElement;
  const config = { attributes: true };
  this.mutationObserver = new MutationObserver((mutation) => {
    const target = mutation[0].target as HTMLElement;
    //some code here to execute based on some conditions and to remove the observer 
   }
  });
this.mutationObserver.observe(this.refElement, config);}
  • Related