DEV Community

Cover image for How to use ResizeObserver with Angular

How to use ResizeObserver with Angular

Christian Kohler on February 24, 2020

tl;dr Sometimes we need to execute JavaScript when an element is resized. Current solutions are based on the viewport dimension, not on...
Collapse
 
kresdjan profile image
christian • Edited

Great article, thanks for creating the package and for write up. 👍
I seem to have use toFixed() or something similar entry.contentRect.width.toFixed() to get the same result as you, otherwise the width is, 967.40625.

Collapse
 
rajkumarmp profile image
Rajkumar.MP

Mutation Observer also another option to observe the Element changes in DOM and it's supported all browsers.

MutationObserver MDN

Collapse
 
sebastiandg7 profile image
Sebastián Duque G

Man, this is dope for responsiveness in angular! Thanks a lot! 🔥

Collapse
 
bsully75 profile image
Bryan Sullivan

I'm curious how I'd be able to test the Angular implementation using Jasmine? I'm not very knowledgeable about unit testing or the Jasmine framework, but have been asked to write unit tests for this functionality. Specifically these:

  • When host native element width changes, the width property should change with it.
  • The observer should stop observing upon ngOnDestroy.

Would it be possible to provide a sample spec file in your StackBlitz example? Any help would be greatly appreciated.

Collapse
 
stefankandlbinder profile image
Stefan Kandlbinder

Hi,
thx for sharing.
Am i right, that your code is producing a new instance of ResizeObserver for every element?
I discovered this article groups.google.com/a/chromium.org/g... and in there it is said that there will be a huge performance improvement if you create the ResizeObserver as a Singleton...

Regards
Stefan

Collapse
 
salimchemes profile image
Salim Chemes

Great explanation! Thanks for sharing.
Quick question, does it only work with display: block; ? If I try to remove this property then is not working anymore.

Collapse
 
kresdjan profile image
christian

I just updated to Catalina 10.15.0 and Safari 13.1 now support ResizeObserver

Collapse
 
roniccolo profile image
Marius Cimpoeru

I have created this account just to say Thank you!

Collapse
 
jpalmowski profile image
James Palmowski

Thanks for mentioning ngZone and change detection, saved me some grief!