Detecting real time window size changes in Angular 4

Ronit Oommen picture Ronit Oommen · Jul 27, 2017 · Viewed 131k times · Source

I have been trying to build a responsive nav-bar and do not wish to use a media query, so I intend to use *ngIF with the window size as a criterion. But I have been facing a problem as I am unable to find any method or documentation on Angular 4 window size detection. I have also tried the JavaScript method, but it is not supported.

I have also tried the following:

constructor(platform: Platform) {
    platform.ready().then((readySource) => {
        console.log('Width: ' + platform.width());
        console.log('Height: ' + platform.height());
    });
}

...which was used in ionic.

And screen.availHeight, but still no success.

Answer

Eduardo Vargas picture Eduardo Vargas · Jul 27, 2017

To get it on init

public innerWidth: any;
ngOnInit() {
    this.innerWidth = window.innerWidth;
}

If you wanna keep it updated on resize:

@HostListener('window:resize', ['$event'])
onResize(event) {
  this.innerWidth = window.innerWidth;
}