Cristiano
Cristiano

Reputation: 1813

How to detect changes on style.display of a HTML element inside a component?

I'm learning and playing with angular 2 and SCSS in context of a responsive mobile page.

I have a SCSS mixin that detects the size of the browser (by media queries) and it sets the display property of some associated elements in order to hidden them when small devices are being used.

And I would like to have the component notified when that change have happen.

How to do that?

Upvotes: 0

Views: 329

Answers (1)

BeetleJuice
BeetleJuice

Reputation: 40896

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}`)
)

Upvotes: 1

Related Questions