Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can detect window resize instantly in angular 2?

Tags:

Some features in my component turn on or off depend on browser size, therefore I want to check browser width on resize event. However, I could do it using OnInit method. But I need to refresh browser when resize happened to update browser width

 ngOnInit() {      if (window.innerWidth <= 767){        ---- do something       }    } 

I tried to use OnChanges method, but it does not work either.

OnChanges(changes:SimpleChanges){ console.log( 'width:====>' + changes[window.innerWidth].currentValue);   if ( changes[window.innerWidth].currentValue <= 767 ){       ---- do something } 

}

is there any suggestions or alternative way to accomplish this?

like image 259
kero Avatar asked Sep 02 '16 20:09

kero


People also ask

What is use of $( window resize ();?

Definition and Usage The resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.


2 Answers

You could just put handler on resize event over window object, but this will allow you to put only single resize event, latest registered event on onresize will work.

constructor(private ngZone:NgZone) {     window.onresize = (e) =>     {         //ngZone.run will help to run change detection         this.ngZone.run(() => {             console.log("Width: " + window.innerWidth);             console.log("Height: " + window.innerHeight);         });     }; } 

To make it more angular way use @HostListener('window:resize') inside your component, which will allow to call your resize function(on which HostListner decorator has been mount) on resize of window.

@HostListener('window:resize', ['$event']) onResize(event){    console.log("Width: " + event.target.innerWidth); } 
like image 123
Pankaj Parkar Avatar answered Sep 27 '22 18:09

Pankaj Parkar


Use HostListener. You should probably debounce the resize event though before doing anything, it will fire everytime the size changes which could be dozens or hundreds of times in a few milliseconds as the user drags the window size.

import { Component, HostListener } from '@angular/core';  @Component({...}) class TestComponent {     @HostListener('window:resize')     onWindowResize() {         //debounce resize, wait for resize to finish before doing stuff         if (this.resizeTimeout) {             clearTimeout(this.resizeTimeout);         }         this.resizeTimeout = setTimeout((() => {             console.log('Resize complete');         }).bind(this), 500);     } } 
like image 39
Alex Egli Avatar answered Sep 27 '22 16:09

Alex Egli