responsive.directive.ts 1.22 KB
Newer Older
Shane Eckenrode's avatar
Shane Eckenrode committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
import { Directive, HostBinding, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { ResponsiveService } from './responsive.service';
import { ScreenSize } from './screen-size.model';

@Directive({
  selector: '[utResponsive]'
})
export class ResponsiveDirective implements OnInit, OnDestroy {
  @HostBinding('class.desktop')
  public isDesktop = false;
  @HostBinding('class.tablet')
  public isTablet = false;
  @HostBinding('class.tablet-sm')
  public isSmallTablet = false;
  @HostBinding('class.mobile')
  public isMobile = false;

  private destroyed$ = new Subject<any>();

  constructor(private responsiveService: ResponsiveService) {}

  ngOnInit(): void {
    this.responsiveService.currentScreenSize$
      .pipe(
        filter(size => !!size),
        takeUntil(this.destroyed$)
      )
      .subscribe((size: ScreenSize) => {
31 32 33 34
        this.isMobile = size === ScreenSize.MOBILE;
        this.isSmallTablet = size === ScreenSize.TABLET_SM;
        this.isTablet = size === ScreenSize.TABLET;
        this.isDesktop = size === ScreenSize.DESKTOP;
Shane Eckenrode's avatar
Shane Eckenrode committed
35 36 37 38 39 40 41 42
      });
  }

  public ngOnDestroy(): void {
    this.destroyed$.next();
    this.destroyed$.complete();
  }
}