角度窗口大小调整事件

2022-08-29 23:51:09

我想根据窗口重新调整大小事件(加载和动态)执行一些任务。

目前我有我的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);
    }
}

如何从此事件对象中检索宽度和高度?

谢谢。


答案 1
<div (window:resize)="onResize($event)"
onResize(event) {
  event.target.innerWidth;
}

或使用 HostListener 装饰器

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

支持的全局目标是 、 和 。windowdocumentbody

Https://github.com/angular/angular/issues/13248 在Angular中实现之前,性能最好是命令性地订阅DOM事件,并使用RXJS来减少事件的数量,如其他一些答案所示。


答案 2

我知道这是很久以前问过的,但现在有更好的方法可以做到这一点!我不确定是否有人会看到这个答案。显然,您的导入:

import { fromEvent, Observable, Subscription } from "rxjs";

然后在您的组件中:

resizeObservable$: Observable<Event>
resizeSubscription$: Subscription

ngOnInit() {
    this.resizeObservable$ = fromEvent(window, 'resize')
    this.resizeSubscription$ = this.resizeObservable$.subscribe( evt => {
      console.log('event: ', evt)
    })
}

那么一定要取消订阅销毁!

ngOnDestroy() {
    this.resizeSubscription$.unsubscribe()
}