1

In one of my controllers I have :

 @HostListener('window:resize')
onResize() {
this.currentWindowWidth = window.innerWidth;
}

and based on the window Width, I render different views. One of which needs to do some calculations. But since the change detection mechanism fires too often, this really slows down the app and there's a delay.

How are such situations managed best?

Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
  • You can use `Observable.fromEvent(window, 'resize').throttleTime(200)...` or `Observable.fromEvent(window, 'resize').debounceTime(200)...`, as explained in [this answer](https://stackoverflow.com/a/36849347/1009922). – ConnorsFan Jan 18 '18 at 17:43
  • Possibly of interest: https://stackoverflow.com/questions/44634992/debounce-hostlistener-event – match Jan 18 '18 at 17:44

1 Answers1

2

That's not related to Angular change detection, it's the resize event that happens that often

Also @HostListener() is currently not a good option to list to events that are emitted that frequently https://github.com/angular/angular/issues/13248

You can use

constructor(private zone: NgZone) {
  this.zone.runOutsideAngular(() => {
    Observable.fromEvent(window, 'resize')
        .debounceTime(100)
        .subscribe((event) => {
          this.zone.run(() => {
            this.currentWindowWidth = window.innerWidth;
          });
        });
  });
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567