Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material2: Show/Hide md-sidenav depending on media

i would like to open the md-sidenav on large screen and close it on mobile device. What would be the right way to do it inside my application?

Is there any possibility to query the media inside angular2 component?

like image 734
Alex Avatar asked Oct 29 '16 16:10

Alex


2 Answers

Inside of component class i've defined a reference to the sidenav and listening to the window resize events. Depending on the window.innerWith you can build your logic.

  @ViewChild('sidenav') sidenav: MdSidenav

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.configureSideNav()
  }

  configureSideNav() {
    this.smallScreen = window.innerWidth < 501 ? true : false
    if (!this.smallScreen) {
      this.sidenav.mode = "side"
      this.sidenav.opened = true
    } else {
      this.sidenav.mode = 'over'
      this.sidenav.opened = false
    }
  }
like image 160
Alex Avatar answered Sep 30 '22 16:09

Alex


i've just found a little bit better approach to listen to screen changes in Angular: https://github.com/angular/flex-layout/wiki/ObservableMedia

it's a Angular Flex Layout module that provides the mediaQuery activations notifications as observable. so there is no need to listen to create a resize listener manually.

besides, MediaChange Class provides handy aliases (lg, md, xs etc.) that can be used to make decisions about screen size-specific expressions.

check out examples on their wiki-page.

like image 21
AndyGrey Avatar answered Sep 30 '22 15:09

AndyGrey