You can use Observable.fromEvent()
to listen for any DOM event. By listening to the Window's resize
event, you will be notified every time the browser window size changes. The Observable below will emit objects with a w
and h
property for window width and height immediately upon subscription and again every time the window is resized.
windowSize$:Observable<{w:number,h:number}> =
Observable.fromEvent(window,
'resize',
()=> {return {w:window.innerWidth, h:window.innerHeight}})
//limits to one event every 500ms
.debounceTime(500)
//emit current value immediately
.startWith({w:window.innerWidth, h:window.innerHeight});
You may need to use document.documentElement.clientWidth
or .clientHeight
instead to get the browser size (see this other question).
Here is how you would use this observable:
windowSize$.subscribe(newSize =>
console.log(`New: width=${newSize.w}, height=${newSize.h}`)
)