Detecting real time window size changes in Angular 4
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;}
If you want to react on certain breakpoints (e.g. do something if width is less than 768px), you can also use BreakpointObserver:
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';{ ... }const isSmallScreen = breakpointObserver.isMatched('(max-width: 599px)');
or even listen to changes to that breakpoint:
breakpointObserver.observe([ '(max-width: 768px)' ]).subscribe(result => { if (result.matches) { doSomething(); } else { // if necessary: doSomethingElse(); } });
If you'd like you components to remain easily testable you should wrap the global window object in an Angular Service:
import { Injectable } from '@angular/core';@Injectable()export class WindowService { get windowRef() { return window; }}
You can then inject it like any other service:
constructor( private windowService: WindowService) { }
And consume...
ngOnInit() { const width= this.windowService.windowRef.innerWidth; }