Detecting real time window size changes in Angular 4

后端 未结 9 744
孤独总比滥情好
孤独总比滥情好 2020-12-04 05:44

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

9条回答
  •  清歌不尽
    2020-12-04 06:47

    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;
      }
    

提交回复
热议问题