Here is a better way to do it. Based on Birowsky's answer.
Step 1: Create an angular service
with RxJS Observables.
import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; @Injectable() export class WindowService { height$: Observable<number>; //create more Observables as and when needed for various properties hello: string = "Hello"; constructor() { let windowSize$ = new BehaviorSubject(getWindowSize()); this.height$ = (windowSize$.pluck('height') as Observable<number>).distinctUntilChanged(); Observable.fromEvent(window, 'resize') .map(getWindowSize) .subscribe(windowSize$); } } function getWindowSize() { return { height: window.innerHeight //you can sense other parameters here }; };
Step 2: Inject the above service
and subscribe to any of the Observables
created within the service wherever you would like to receive the window resize event.
import { Component } from '@angular/core'; //import service import { WindowService } from '../Services/window.service'; @Component({ selector: 'pm-app', templateUrl: './componentTemplates/app.component.html', providers: [WindowService] }) export class AppComponent { constructor(private windowService: WindowService) { //subscribe to the window resize event windowService.height$.subscribe((value:any) => { //Do whatever you want with the value. //You can also subscribe to other observables of the service }); } }
A sound understanding of Reactive Programming will always help in overcoming difficult problems. Hope this helps someone.