Recently I had an Angular component that needed to be manually sized based on the window’s size. Admittedly, this is pretty annoying, but the user experience was so much better than anything I could come up with using straight CSS. It worked fine to get the dimensions of the window and calculate the width and height when the component initialized, but what about if the window is resized?
Observables
I’m still wrapping my head around rxjs/observables, but I’m starting to like them more and more. It turns out, you can easily hook up an Observable to a window event and even throttle the amount of times that the Observable emits the event. This works great for detecting a window resize, because we don’t necessarily need it to happen instantaneously… doing so would cause the CPU to be a little bit angry.
fromEvent
This function automatically takes an event and converts it in to an Observable. Then we can use debounceTime to throttle the messages, only sending the last message if another message hasn’t been emitted in the last 500ms. Our Subject can then be invoked, emitting the data that we actually care about (in this case, the screen width and screen height):