猿问

角度窗口调整大小事件

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


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

    }

}

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


谢谢。


HUX布斯
浏览 485回答 3
3回答

倚天杖

我只是想提出另一种方法。您也可以在@Component()-decorator中添加主机绑定。您可以将事件和所需的函数调用放在主机元数据属性中,如下所示:@Component({&nbsp; selector: 'app-root',&nbsp; templateUrl: './app.component.html',&nbsp; styleUrls: ['./app.component.css'],&nbsp; host: {&nbsp; &nbsp; '(window:resize)': 'onResize($event)'&nbsp; }})export class AppComponent{&nbsp; &nbsp;onResize(event){&nbsp; &nbsp; &nbsp;event.target.innerWidth; // window width&nbsp; &nbsp;}}

慕神8447489

正确的方法是利用EventManager类绑定事件。这使您的代码可以在其他平台上工作,例如,使用Angular Universal进行服务器端渲染。import { EventManager } from '@angular/platform-browser';import { Observable } from 'rxjs/Observable';import { Subject } from 'rxjs/Subject';import { Injectable } from '@angular/core';@Injectable()export class ResizeService {&nbsp; get onResize$(): Observable<Window> {&nbsp; &nbsp; return this.resizeSubject.asObservable();&nbsp; }&nbsp; private resizeSubject: Subject<Window>;&nbsp; constructor(private eventManager: EventManager) {&nbsp; &nbsp; this.resizeSubject = new Subject();&nbsp; &nbsp; this.eventManager.addGlobalEventListener('window', 'resize', this.onResize.bind(this));&nbsp; }&nbsp; private onResize(event: UIEvent) {&nbsp; &nbsp; this.resizeSubject.next(<Window>event.target);&nbsp; }}组件中的用法很简单,只需将此服务作为提供程序添加到您的app.module中,然后将其导入组件的构造函数中即可。import { Component, OnInit } from '@angular/core';@Component({&nbsp; selector: 'my-component',&nbsp; template: ``,&nbsp; styles: [``]})export class MyComponent implements OnInit {&nbsp; private resizeSubscription: Subscription;&nbsp; constructor(private resizeService: ResizeService) { }&nbsp; ngOnInit() {&nbsp; &nbsp; this.resizeSubscription = this.resizeService.onResize$&nbsp; &nbsp; &nbsp; .subscribe(size => console.log(size));&nbsp; }&nbsp; ngOnDestroy() {&nbsp; &nbsp; if (this.resizeSubscription) {&nbsp; &nbsp; &nbsp; this.resizeSubscription.unsubscribe();&nbsp; &nbsp; }&nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答