我想执行一些基于窗口重新大小事件(在加载和动态)的任务。

目前我的DOM如下:

<div id="Harbour">
    <div id="Port" (window:resize)="onResize($event)" >
        <router-outlet></router-outlet>
    </div>
</div>

事件正确触发

export class AppComponent {
    onResize(event) {
        console.log(event);
    }
}

我如何从这个事件对象检索宽度和高度?

谢谢。


当前回答

下面的代码让我们观察Angular中任何给定div的大小变化。

<div #observed-div>
</div>

然后在组件中:

oldWidth = 0;
oldHeight = 0;

@ViewChild('observed-div') myDiv: ElementRef;
ngAfterViewChecked() {
  const newWidth = this.myDiv.nativeElement.offsetWidth;
  const newHeight = this.myDiv.nativeElement.offsetHeight;
  if (this.oldWidth !== newWidth || this.oldHeight !== newHeight)
    console.log('resized!');

  this.oldWidth = newWidth;
  this.oldHeight = newHeight;
}

其他回答

下面是最新版本的Rxjs对@GiridharKamik答案的更新。

import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject, fromEvent } from 'rxjs';
import { pluck, distinctUntilChanged, map } from 'rxjs/operators';

@Injectable()
export class WindowService {
    height$: Observable<number>;
    constructor() {
        const windowSize$ = new BehaviorSubject(getWindowSize());

        this.height$ = windowSize$.pipe(pluck('height'), distinctUntilChanged());

        fromEvent(window, 'resize').pipe(map(getWindowSize))
            .subscribe(windowSize$);
    }

}

function getWindowSize() {
    return {
        height: window.innerHeight
        //you can sense other parameters here
    };
};

在Angular2(2.1.0)中,我使用ngZone来捕获屏幕更改事件。

看一下这个例子:

import { Component, NgZone } from '@angular/core';//import ngZone library
...
//capture screen changed inside constructor
constructor(private ngZone: NgZone) {
    window.onresize = (e) =>
    {
        ngZone.run(() => {
            console.log(window.innerWidth);
            console.log(window.innerHeight);
        });
    };
}

希望这对你有所帮助!

基于@cgatian的解决方案,我建议简化如下:

import { EventManager } from '@angular/platform-browser';
import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class ResizeService {

  public onResize$ = new EventEmitter<{ width: number; height: number; }>();

  constructor(eventManager: EventManager) {
    eventManager.addGlobalEventListener('window', 'resize',
      e => this.onResize$.emit({
        width: e.target.innerWidth,
        height: e.target.innerHeight
      }));
  }
}

用法:

import { Component } from '@angular/core';
import { ResizeService } from './resize-service';

@Component({
  selector: 'my-component',
  template: `{{ rs.onResize$ | async | json }}`
})
export class MyComponent {
  constructor(private rs: ResizeService) { }
}

我所做的就像Johannes Hoppe建议的那样:

import { EventManager } from '@angular/platform-browser'; import { Injectable, EventEmitter } from '@angular/core'; @Injectable() export class ResizeService { public onResize$ = new EventEmitter<{ width: number; height: number; }>(); constructor(eventManager: EventManager) { eventManager.addGlobalEventListener('window', 'resize', event => this.onResize$.emit({ width: event.target.innerWidth, height: event.target.innerHeight })); } getWindowSize(){ this.onResize$.emit({ width: window.innerWidth, height: window.innerHeight }); } }

在app.component.ts:

Import { ResizeService } from ".shared/services/resize.service" import { Component } from "@angular/core" @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent{ windowSize: {width: number, height: number}; constructor(private resizeService: ResizeService){ } ngOnInit(){ this.resizeService.onResize$.subscribe((value) => { this.windowSize = value; }); this.resizeService.getWindowSize(); } }

然后在你的app.component.html中:

<router-outlet *ngIf = "windowSize? "宽度> 1280 && windowSize?。高度> 700;errorComponent”> < / router-outlet > < ng-template # errorComponent > < app-error-component > < / app-error-component > < / ng-template >

我写这个库是为了找到Angular中组件边界大小改变(重新调整大小)的方法,希望能帮助到其他人。你可以把它放在根组件上,会做和窗口大小调整一样的事情。

步骤1:导入模块

import { BoundSensorModule } from 'angular-bound-sensor';

@NgModule({
  (...)
  imports: [
    BoundSensorModule,
  ],
})
export class AppModule { }

步骤2:添加如下指令

<简单的组件boundSensor > < /简单的组件>

步骤3:接收边界大小的详细信息

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

@Component({
  selector: 'simple-component'
  (...)
})
class SimpleComponent {
  @HostListener('resize', ['$event'])
  onResize(event) {
    console.log(event.detail);
  }
}