Search code examples
angularangular2-templateangular2-services

Angular 2 Media Queries


I want to know that does Angular 2 provides a way to determine the client's device (large screen, medium or smalls screen) or may be screen width on the basic of which some contents could be shown or hidden (removed from dom).


Solution

  • HostListener

    One way is to use the HostListener decorator. The decorated method will be invoked when the host element emits the specified event.

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

    Via ngZone

    Another way is to import ngZone into your component. Then you can use NgZone to check the onresize event.

    constructor(ngZone:NgZone) {
      window.onresize = (e) => {
        ngZone.run(() => {
            this.width = window.innerWidth;
            this.height = window.innerHeight;
        });
      };
    }
    

    After that you can use the [hidden] attribute to hide content depends from your width or height value.