Material2 Auto hide sidenav on smaller screens

Here's one way of doing it.

app.component.html

<md-sidenav-layout>
   <md-sidenav #sidenav mode="side"><label>Sidenav</label></md-sidenav>
   <button md-raised-button="md-raised-button" color="primary" (click)="sidenav.toggle()">Open Sidenav</button>
</md-sidenav-layout>

app.component.ts

import { Component, ViewChild, HostListener } from '@angular/core';
import {MdSidenav} from "@angular/material";

@Component({
    moduleId: module.id,
    selector: 'my-app',
    templateUrl: 'app.component.html'
})

export class AppComponent {
    @ViewChild('sidenav') sidenav: MdSidenav;

    @HostListener('window:resize', ['$event'])
    onResize(event) {
        if (event.target.innerWidth < 500) {
            this.sidenav.close();
        }
    }
}

If you are using Angular Flex-Layout you could make use of the MediaObserver service and bind it to the opened property of the mat-sidenav.

@Component({
selector: 'my-component',
template: `  
  <md-sidenav-container>
    <md-sidenav
      mode="over"
      [opened]="!media.isActive('xs')">
    </md-sidenav>
    ...        
  </md-sidenav-container>`
})
export class MyComponent {    
   constructor(public media: MediaObserver) {}
}

This will hide the sidenav on mobile viewport sizes.


Hi this is how i solved this problem.

App.component.html

<mat-sidenav-container class="container">
    <mat-sidenav class="sidenav" #sidenav mode="side" [opened]="screenWidth> 640">
        <mat-toolbar color="primary">
            <h1>Sidenav</h1>
        </mat-toolbar>
        <mat-list role="list">
            <mat-list-item role="listitem">Item 1</mat-list-item>
            <mat-list-item role="listitem">Item 2</mat-list-item>
            <mat-list-item role="listitem">Item 3</mat-list-item>
        </mat-list>
    </mat-sidenav>
    <mat-sidenav-content>
        <div class="content-container">
            <h1> text content</h1>
            <p>
                What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the
                printing and typesetting industry. Lorem Ipsum has been the         
            </p>
        </div>
    </mat-sidenav-content>
</mat-sidenav-container>

app.component.ts

import { Component, ViewChild, HostListener  } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import {MatSidenav} from '@angular/material/sidenav';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  screenWidth: number;
  private screenWidth$ = new BehaviorSubject<number>(window.innerWidth);
  @ViewChild('sidenav') sidenav: MatSidenav;
  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.screenWidth$.next(event.target.innerWidth);
  }
  constructor() { }

  ngOnInit() {
    this.screenWidth$.subscribe(width => {
      this.screenWidth = width;
    });
  }
}

here is the code in slackblitz