【问题标题】:Angular2 get window width onResizeAngular2获取窗口宽度onResize
【发布时间】:2016-06-02 08:09:19
【问题描述】:

试图弄清楚如何在 Angular2 中调整事件大小时获取窗口宽度。这是我的代码:

export class SideNav {

    innerWidth: number;

    constructor(private window: Window){

        let getWindow = function(){
          return window.innerWidth;
        };

        window.onresize = function() {
          this.innerWidth = getWindow();
          console.log(getWindow());
        };
} 

我在 bootstrap.ts 文件中全局导入窗口提供程序,使用提供来获得跨我的应用程序对窗口的访问权限。我遇到的问题是这确实给了我一个窗口大小,但是在调整窗口大小时 - 即使窗口改变大小,它也会一遍又一遍地重复相同的大小。 有关 console.log 示例,请参见图像: Screenshot image

我的总体目标是能够将窗口编号设置为变量 onresize,以便我可以在模板中访问它。关于我在这里做错了什么有什么想法吗?

谢谢!

【问题讨论】:

    标签: css typescript angular angular2-directives


    【解决方案1】:
    <div (window:resize)="onResize($event)"
    
    onResize(event) {
      event.target.innerWidth; 
    }
    

    在组件模板中的子元素上获得滚动事件通知

    或者监听组件宿主元素本身

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

    【讨论】:

    • 你为什么注释掉 @Hostlistener ?对我来说,它只能在没有注释斜杠的情况下工作,但它可以完美地工作:-)
    • 这是一种替代方式。您可以将它添加到模板中的元素中,如第一个代码片段所示,或者使用@HostListener() 来监听组件宿主元素本身。我更新了我的答案以使其更清楚。
    【解决方案2】:

    在这种情况下,您需要手动运行更改检测。当您从 Angular 的外部上下文修改组件变量时,基本上 resize 事件不会被 Angular2 更改检测系统修补。

    代码

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

    我倒是建议你去this answer,看起来更干净

    【讨论】:

    • 了解更改检测很有趣-但我真的很高兴您向我指出 Observable 解决方案-我能够以非常可重用的干净方式为全局窗口宽度和高度添加新服务有了它 - 非常感谢你!
    【解决方案3】:

    使用NgZone 触发变更检测:

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

    【讨论】:

    • ngZone 的有趣想法 - 我必须尝试一下!目前使用可观察的实现来自动检测更改。
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2013-10-10
    • 2018-08-12
    • 2012-01-21
    • 2018-10-23
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多