Angular window resize event

DanAbdn picture DanAbdn · Feb 20, 2016 · Viewed 282.4k times · Source

I would like to perform some tasks based on the window re-size event (on load and dynamically).

Currently I have my DOM as follows:

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

The event correctly fires

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

How do I retrieve the Width and Height from this event object?

Thanks.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Feb 20, 2016
<div (window:resize)="onResize($event)"
onResize(event) {
  event.target.innerWidth;
}

or using the HostListener decorator:

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

Supported global targets are window, document, and body.

Until https://github.com/angular/angular/issues/13248 is implemented in Angular it is better for performance to subscribe to DOM events imperatively and use RXJS to reduce the amount of events as shown in some of the other answers.