How I can detect window resize instantly in angular 2?

前端 未结 3 1109
悲&欢浪女
悲&欢浪女 2021-02-04 00:26

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 n

相关标签:
3条回答
  • 2021-02-04 00:57

    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);
    }
    
    0 讨论(0)
  • 2021-02-04 00:57

    An easier way would be using the resize method on the html block that you want to detect:

    <div class="some-class" (window:resize)="onResize($event)">...</div>
    

    Then in your .ts file you can just add:

    onResize(event) {
    
       const innerWidth = event.target.innerWidth;
       console.log(innerWidth);
    
       if (innerWidth <= 767) {
          ...do something
       }
    }
    

    Add this outside of the ngOnInit() {} unless you wanted the window size on page load.

    When you resize your window, you'll see the console.log

    0 讨论(0)
  • 2021-02-04 01:17

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题