Search code examples
javascriptangulartypescriptangular2-changedetection

Is there any 'passive' way to get element style from @ViewChild style dynamically in Angular2?


For example, there is an element in the template using a local variable #targetElement which aims to get its current width whenever it needs. But I don't want to programmatically calculate the style. Tried with a setter with @ViewChild annotation

get: to get the style from the template

set: to set the value to the component

@ViewChild('targetElement')
set imgWidth(content: ElementRef) {
  if (content) {
    console.log('Current width is: ' + content.nativeElement.clientWidth);
  }
}

But it can only get a 0 and it won't update when the page is resized, or any change to the window. So, the question is how I can passively set the #targetElement into my component in anytime?

Write a setter in ngDoCheck or ngAfterViewChecked seems killing the performance.


Solution

  • You can use resizeObserver

    Resize Observer is a new JavaScript API that’s very similar to other observer APIs like the Intersection Observer API. It allows for elements to be notified when their size changes.

    Install polyfill that may be used for browsers back to Internet Explorer 11

    npm i resize-observer-polyfill
    
    var observer = new ResizeObserver( resizeObserverEntries => {
        for (let entry of resizeObserverEntries) {
            const rect = entry.contentRect;
            console.log('Element:', entry.target);
            console.log(`Element size: ${rect.width}px x ${rect.height}px`);
            console.log(`Element padding: ${rect.top}px ; ${rect.left}px`);
        }
    });
    

    StackBlitz:https://stackblitz.com/edit/resize-observer

    ResizeObserver: It’s Like document.onresize for Elements Documentation:https://developers.google.com/web/updates/2016/10/resizeobserver Check this:https://www.sitepen.com/blog/2018/06/04/exploring-the-resize-observer-proposal/