Search code examples
angularresizeangular6

Angular 6 service resize event


Is it possible to listen for a window resize from a Angular6 service? I can do it from a component using:

 @HostListener('window:resize', ['$event'])
  onResize(event) {
    //perform actions
  }

This does not seem to be working for a service however.


Solution

  • In this case, you may subscribe to 'window:resize' in app.component and have a service which will handle all the data. Depends on what do you want to do with it.

    just for example if you want just to store(and share) the window size you should have a service:

    import { Injectable } from '@angular/core';
    import { Subject, Observable } from 'rxjs';
    
    @Injectable() // could be @Injectable({ providedIn: 'root' }) in 6+ version
    export class ResizeService {
    
      currentSize$: Subject<number|string> = new Subject<number|string>();
    
      getSize(): Observable<number|string> {
        return this.currentSize$.asObservable();
      }
    
      setSize(size: number|string): void {
       this.currentSize$.next(size);
      }
    
    }
    

    Then in your app.component.ts;

    import { Component } from '@angular/core';
    import { ResizeService } from '<path/to/service>';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      constructor(private resizeService: ResizeService) {}
    
      resizeHandler($event): void {
        this.resizeService.setSize($event.target.innerWidth);
      }
    }
    

    In any component that you want to get these values:

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subject, Observable } from 'rxjs'
    import { takeUntil } from 'rxjs/operators';
    import { ResizeService } from '<path/to/service>';
    
    @Component({
      selector: 'app-my-component',
      templateUrl: './my.component.html',
      styleUrls: ['./my.component.css']
    })
    export class MyComponent implements OnInit, OnDestroy {
    
      private unsubscribeHelper$: Subject<void> = new Subject<void>();
      public size: number | string;     
    
      constructor(private resizeService: ResizeService) {}
    
      ngOnInit(): void {
        this.resizeService.getSize().pipe(takeUntil(this.unsubscribeHelper$))
          .subscribe((size: number | string) => this.size = size);
      }
    
      ngOnDestroy(): void {
        this.unsubscribeHelper$.next();
        this.unsubscribeHelper$.complete();
      }
    }
    

    So far this is the most universal solution to cover most of cases when you need to process data through the service and share it among the application