本文介绍了我如何才能在角度2中立即检测窗口大小调整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

some features in my component turn on or off depend on browser size therefore i want to check browser width on resize event, however i could do it using On Init method but , i need to refresh browser when resize happened to update browser width

 ngOnInit() {
     if (window.innerWidth <= 767){
       ---- do something
      }
   }

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

however i tried to use OnChanges method but it does not work either

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

}

有什么建议或其他方法可以实现这一目标吗?

is there any suggestions or alternative way to accomplish this ?

推荐答案

您可以将处理程序置于window对象上的resize事件上,但这仅允许您放置单个resize事件(最新注册的事件)在onresize上可以使用.

You could just put handler on resize event over window object, but this will allow you to put only single resize event, latest registered event on onresize will work.

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

要使其更具角度,请在组件内部使用@HostListener('window:resize'),这将允许在窗口的resize上调用resize函数(已将HostListner装饰器安装在其上).

To make it more angular way use @HostListener('window:resize') inside your component, which will allow to call your resize function(on which HostListner decorator has been mount) on resize of window.

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

这篇关于我如何才能在角度2中立即检测窗口大小调整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:06