Html 检测 Angular 4 中的实时窗口大小变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45350716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:48:26  来源:igfitidea点击:

Detecting real time window size changes in Angular 4

htmlangulardom-events

提问by Ronit Oommen

I have been trying to build a responsive nav-bar and do not wish to use a media query, so I intend to use *ngIFwith the window size as a criterion. But I have been facing a problem as I am unable to find any method or documentation on Angular 4 window size detection. I have also tried the JavaScript method, but it is not supported.

我一直在尝试构建一个响应式导航栏并且不希望使用媒体查询,所以我打算使用*ngIF窗口大小作为标准。但是我一直面临一个问题,因为我找不到关于 Angular 4 窗口大小检测的任何方法或文档。我也尝试过 JavaScript 方法,但它不受支持。

I have also tried the following:

我还尝试了以下方法

constructor(platform: Platform) {
    platform.ready().then((readySource) => {
        console.log('Width: ' + platform.width());
        console.log('Height: ' + platform.height());
    });
}

...which was used in ionic.

...用于离子。

And screen.availHeight, but still no success.

并且screen.availHeight,但仍然没有成功。

回答by Eduardo Vargas

To get it on init

在 init 上获取它

public innerWidth: any;
ngOnInit() {
    this.innerWidth = window.innerWidth;
}

If you wanna keep it updated on resize:

如果您想在调整大小时保持更新:

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

回答by Jeremy Benks

If you want to react on certain breakpoints (e.g. do something if width is less than 768px), you can also use BreakpointObserver:

如果你想对某些断点做出反应(例如,如果宽度小于 768px 做一些事情),你也可以使用 BreakpointObserver:

import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';

{ ... }

const isSmallScreen = breakpointObserver.isMatched('(max-width: 599px)');

or even listen to changes to that breakpoint:

甚至监听该断点的变化:

breakpointObserver.observe([
  '(max-width: 768px)'
    ]).subscribe(result => {
      if (result.matches) {
        doSomething();
      } else {
        // if necessary:
        doSomethingElse();
      }
    });

回答by robbannn

The documentation for Platformwidth()and height(), it's stated that these methods use window.innerWidthand window.innerHeightrespectively. But using the methods are preffered since the dimensions are cached values, which reduces the chance of multiple and expensive DOM reads.

对于文档Platformwidth()height(),它指出,这些方法使用window.innerWidthwindow.innerHeight分别。但是优先使用这些方法,因为维度是缓存值,这减少了多次和昂贵的 DOM 读取的机会。

import { Platform } from 'ionic-angular';

...
private width:number;
private height:number;

constructor(private platform: Platform){
    platform.ready().then(() => {
        this.width = platform.width();
        this.height = platform.height();
    });
}

回答by Kildareflare

If you'd like you components to remain easily testable you should wrap the global window object in an Angular Service:

如果您希望组件保持易于测试,您应该将全局窗口对象包装在 Angular 服务中:

import { Injectable } from '@angular/core';

@Injectable()
export class WindowService {

  get windowRef() {
    return window;
  }

}

You can then inject it like any other service:

然后你可以像任何其他服务一样注入它:

constructor(
    private windowService: WindowService
) { }

And consume...

并且消耗...

  ngOnInit() {
      const width= this.windowService.windowRef.innerWidth;
  }

回答by Fabián Carrasco

you can use this https://github.com/ManuCutillas/ng2-responsiveHope it helps :-)

你可以使用这个 https://github.com/ManuCutillas/ng2-responsive希望它有帮助:-)

回答by Dhruv Parekh

@HostListener("window:resize", [])
public onResize() {
  this.detectScreenSize();
}

public ngAfterViewInit() {
    this.detectScreenSize();
}

private detectScreenSize() {
    const height = window.innerHeight;
    const width = window.innerWidth;
}

回答by Denis

This is an example of service which I use.

这是我使用的服务示例。

You can get the screen width by subscribing to screenWidth$, or via screenWidth$.value.

您可以通过订阅screenWidth$或通过来获取屏幕宽度screenWidth$.value

The same is for mediaBreakpoint$( or mediaBreakpoint$.value)

对于mediaBreakpoint$( 或mediaBreakpoint$.value) 也是如此

import {
  Injectable,
  OnDestroy,
} from '@angular/core';
import {
  Subject,
  BehaviorSubject,
  fromEvent,
} from 'rxjs';
import {
  takeUntil,
  debounceTime,
} from 'rxjs/operators';

@Injectable()
export class ResponsiveService implements OnDestroy {
  private _unsubscriber$: Subject<any> = new Subject();
  public screenWidth$: BehaviorSubject<number> = new BehaviorSubject(null);
  public mediaBreakpoint$: BehaviorSubject<string> = new BehaviorSubject(null);

  constructor() {}

  init() {
    this._setScreenWidth(window.innerWidth);
    this._setMediaBreakpoint(window.innerWidth);
    fromEvent(window, 'resize')
      .pipe(
        debounceTime(1000),
        takeUntil(this._unsubscriber$)
      ).subscribe((evt: any) => {
        this._setScreenWidth(evt.target.innerWidth);
        this._setMediaBreakpoint(evt.target.innerWidth);
      });
  }

  ngOnDestroy() {
    this._unsubscriber$.next();
    this._unsubscriber$.complete();
  }

  private _setScreenWidth(width: number): void {
    this.screenWidth$.next(width);
  }

  private _setMediaBreakpoint(width: number): void {
    if (width < 576) {
      this.mediaBreakpoint$.next('xs');
    } else if (width >= 576 && width < 768) {
      this.mediaBreakpoint$.next('sm');
    } else if (width >= 768 && width < 992) {
      this.mediaBreakpoint$.next('md');
    } else if (width >= 992 && width < 1200) {
      this.mediaBreakpoint$.next('lg');
    } else if (width >= 1200 && width < 1600) {
      this.mediaBreakpoint$.next('xl');
    } else {
      this.mediaBreakpoint$.next('xxl');
    }
  }

}

Hope this helps someone

希望这有助于某人

回答by Rohan Gayen

You may use the typescript getter method for this scenario. Like this

您可以在这种情况下使用 typescript getter 方法。像这样

public get width() {
  return window.innerWidth;
}

And use that in template like this:

并在模板中使用它,如下所示:

<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768 
}"></section>

You won't need any event handler to check for resizing/ of window, this method will check for size every time automatically.

您不需要任何事件处理程序来检查窗口的调整大小/,此方法每次都会自动检查大小。

回答by Harish Mahajan

The answer is very simple. write the below code

答案很简单。编写下面的代码

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
 selector: "app-login",
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;

@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
      this.scrHeight = window.innerHeight;
      this.scrWidth = window.innerWidth;
      console.log(this.scrHeight, this.scrWidth);
}

// Constructor
constructor() {
    this.getScreenSize();
}
}