我怎么能在角度2中检测到窗口大小调整?

ker*_*ero 24 events angular

我的组件中的一些功能打开或关闭取决于浏览器大小因此我想检查调整大小事件上的浏览器宽度,但我可以使用On Init方法,但我需要刷新浏览器调整大小时发生更新浏览器宽度

 ngOnInit() {
     if (window.innerWidth <= 767){
       ---- do something
      }
   }
Run Code Online (Sandbox Code Playgroud)

但是我试图使用OnChanges方法,但它也不起作用

OnChanges(changes:SimpleChanges){
console.log( 'width:====>' + changes[window.innerWidth].currentValue);
  if ( changes[window.innerWidth].currentValue <= 767 ){
      ---- do something
}
Run Code Online (Sandbox Code Playgroud)

}

有任何建议或替代方法来实现这一目标吗?

Pan*_*kar 38

你可以把resize事件上的处理程序放在window对象上,但是这将允许你只放置单个resize事件,最新注册的事件就onresize可以了.

constructor(private ngZone:NgZone) {
    window.onresize = (e) =>
    {
        //ngZone.run will help to run change detection
        this.ngZone.run(() => {
            console.log("Width: " + window.innerWidth);
            console.log("Height: " + window.innerHeight);
        });
    };
}
Run Code Online (Sandbox Code Playgroud)

@HostListener('window:resize')在组件内部使用更多角度方式,这将允许HostListnerresize窗口上调用resize函数(装载器已挂载).

@HostListener('window:resize', ['$event'])
onResize(event){
   console.log("Width: " + event.target.innerWidth);
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,谢谢澄清。我使用了 Host Listener 解决方案,它允许多个调整大小事件(每个组件一个),并且似乎是一种“更有角度的方式”来做事, (2认同)

Ale*_*gli 21

使用HostListener.您可能应该在执行任何操作之前去抖调整大小事件,每次大小更改时都会触发,当用户拖动窗口大小时,这会在几毫秒内发生几十次或几百次.

import { Component, HostListener } from '@angular/core';

@Component({...})
class TestComponent {
    @HostListener('window:resize')
    onWindowResize() {
        //debounce resize, wait for resize to finish before doing stuff
        if (this.resizeTimeout) {
            clearTimeout(this.resizeTimeout);
        }
        this.resizeTimeout = setTimeout((() => {
            console.log('Resize complete');
        }).bind(this), 500);
    }
}
Run Code Online (Sandbox Code Playgroud)


Nos*_*niw 6

更简单的方法是在要检测的html块上使用resize方法:

<div class="some-class" (window:resize)="onResize($event)">...</div>
Run Code Online (Sandbox Code Playgroud)

然后在您的.ts文件中,您只需添加:

onResize(event) {

   const innerWidth = event.target.innerWidth;
   console.log(innerWidth);

   if (innerWidth <= 767) {
      ...do something
   }
}
Run Code Online (Sandbox Code Playgroud)

除非您希望页面加载窗口大小,否则将其添加到外部ngOnInit() {}.

当你调整窗口大小时,你会看到 console.log