使用Angular 4检测窗口大小

时间:2017-07-27 12:22:33

标签: angular

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

我也试过following

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

......用于离子。

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

9 个答案:

答案 0 :(得分:132)

在init上获取它

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

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

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

答案 1 :(得分:11)

如果您想对某些断点做出反应(例如,如果宽度小于768px,请执行某些操作),也可以使用BreakpointObserver:

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

{ ... }

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

或什至聆听对该断点的更改:

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

答案 2 :(得分:7)

这是我使用的服务示例。

您可以通过订阅screenWidth$或通过screenWidth$.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');
    }
  }

}

希望这对某人有帮助

答案 3 :(得分:6)

Platform width()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();
    });
}

答案 4 :(得分:5)

如果希望组件易于测试,则应将全局窗口对象包装在Angular Service中:

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

@Injectable()
export class WindowService {

  get windowRef() {
    return window;
  }

}

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

constructor(
    private windowService: WindowService
) { }

消费...

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

答案 5 :(得分:4)

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

答案 6 :(得分:4)

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

O(n)

答案 7 :(得分:1)

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

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

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

答案 8 :(得分:1)

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

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

并在这样的模板中使用它:

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

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