Angular2 获取窗口宽度 onResize [英] Angular2 get window width onResize

查看:32
本文介绍了Angular2 获取窗口宽度 onResize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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 示例:截图图像

I am importing window provider globally in the bootstrap.ts file using provide to gain access across my app to window. The problem I am having is this does give me a window size, but on resizing the window - it just repeats the same size over and over even if the window changes size. See image for console.log example: Screenshot image

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

My overall goal is to be able to set the window number to a variable onresize so I can have access to it in the template. Any ideas on what I am doing wrong here?

谢谢!

推荐答案

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

这篇关于Angular2 获取窗口宽度 onResize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆