![]() ![]() I hope I could give you an overview over this new API. ![]() ResizeObservers allow us to run code exactly when we need it. Want to try it out? Here is a live example on Stackblitz It's a RxJS observable and you can use all operators with it. NgResizeObserver is created per component and will automatically unsubscribe when the component is destroyed. You can observe multiple elements with one ResizeObserver. Here is an example on how to use ResizeObserver to subscribe to a resize event of an element. Now that we know why we need the new ResizeObserver Api we will take a closer look at it. The ResizeObserver triggers but the window.onresize doesn't. In the graphic below the viewport doesn't change and the sidebar gets expanded. Elements are collapsed or expanded (e.g.This happens when the viewport doesn't change but the elements within change. Running to much code on every onresize could lead to performance problems. Do you see the first window.onresize (colored in red)? We are not interested in this event. This happens when the viewport changes but our component doesn't. Unfortunately window.onchange sometimes fires too often or not at all. We are only interested in events where our component changes its width. □ What's the problem with window.onchange? In this article we will have a look at how it works and how we can use this new API together with Angular. ![]() ResizeObserver ResizeObserver - Web APIs | MDN is a new API to solve exactly this problem. Both solutions are based on the viewport dimension, not the element dimension. This is usually implemented with either window.onchange or matchMedia. But sometimes we need to know when an element is resized and execute some logic in JavaScript. Many changes in screen size or element size can be handled with pure CSS. That's why I've created a library to simplify the usage with Angular. I found it to cumbersome to do it on every component. There are a few steps required to use it properly with Angular. ResizeObserver is a new API which allows us to react to element resizing. ![]() Sometimes we need to execute JavaScript when an element is resized.Ĭurrent solutions are based on the viewport dimension, not on element dimensions. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |