Angular2 get window width onResize

后端 未结 3 1904
广开言路
广开言路 2021-02-02 08:40

Trying to figure out how to get window width on resizing events in Angular2. Here is my code:

export class SideNav {

    innerWidth: number;

    constructor(pr         


        
相关标签:
3条回答
  • 2021-02-02 09:04

    In this case you need to run change detection manually. As you are modifying component variable from outer context of Angular, basically resize event doesn't get monkey patched by Angular2 change detection system.

    Code

    import {ChangeDetectorRef} from 'angular2/core'
    
    export class SideNav {
        innerWidth: number;
    
        constructor(private window: Window, private cdr: ChangeDetectorRef){
    
           let getWindow = () => {
              return window.innerWidth;
           };
    
          window.onresize = () => {
              this.innerWidth = getWindow();
              this.cdr.detectChanges(); //running change detection manually
          };
        }
    }
    

    Rather I'd like to suggest you to go for this answer, which looks more cleaner

    0 讨论(0)
  • 2021-02-02 09:05
    <div (window:resize)="onResize($event)"
    
    onResize(event) {
      event.target.innerWidth; 
    }
    

    to get notified on scroll events on a child element in a components template

    or listen on the components host element itself

    @HostListener('window:resize', ['$event'])
    onResize(event) {
      event.target.innerWidth; 
    }
    
    0 讨论(0)
  • 2021-02-02 09:19

    Use NgZone to trigger change detection:

    constructor(ngZone:NgZone) {
        window.onresize = (e) =>
        {
            ngZone.run(() => {
                this.width = window.innerWidth;
                this.height = window.innerHeight;
            });
        };
    }
    
    0 讨论(0)
提交回复
热议问题