Angular window resize event Angular window resize event javascript javascript

Angular window resize event


<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.


I know this was asked a long time ago, but there is a better way to do this now! I'm not sure if anyone will see this answer though. Obviously your imports:

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

Then in your component:

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

Then be sure to unsubscribe on destroy!

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


@Günter's answer is correct. I just wanted to propose yet another method.

You could also add the host-binding inside the @Component()-decorator. You can put the event and desired function call in the host-metadata-property like so:

@Component({  selector: 'app-root',  templateUrl: './app.component.html',  styleUrls: ['./app.component.css'],  host: {    '(window:resize)': 'onResize($event)'  }})export class AppComponent{   onResize(event){     event.target.innerWidth; // window width   }}