Quantcast
Channel: Angular window resize event - Stack Overflow
Viewing all articles
Browse latest Browse all 20

Answer by Totati for Angular window resize event

$
0
0

There's a ViewportRuler service in angular CDK. It runs outside of the zone, supports orientationchange and resize. It works with server side rendering too.

@Component({  selector: 'my-app',  template: `<p>Viewport size: {{ width }} x {{ height }}</p>  `})export class AppComponent implements OnDestroy {  width: number;  height: number;  private readonly viewportChange = this.viewportRuler    .change(200)    .subscribe(() => this.ngZone.run(() => this.setSize()));  constructor(    private readonly viewportRuler: ViewportRuler,    private readonly ngZone: NgZone  ) {    // Change happens well, on change. The first load is not a change, so we init the values here. (You can use `startWith` operator too.)    this.setSize();  }  // Never forget to unsubscribe!  ngOnDestroy() {    this.viewportChange.unsubscribe();  }  private setSize() {    const { width, height } = this.viewportRuler.getViewportSize();    this.width = width;    this.height = height;  }}

Stackblitz example for ViewportRuler

The benefit is, that it limits change detection cycles (it will trigger only when you run the callback in the zone), while (window:resize) will trigger change detection every time it gets called.


Viewing all articles
Browse latest Browse all 20

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>