How I can detect window resize instantly in angular 2?

前端 未结 3 1108
悲&欢浪女
悲&欢浪女 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 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);
        }
    }
    

提交回复
热议问题