Angular Material: a responsive Sidenav

Frederic Lopes
2 min readSep 9, 2017

--

Hello folks! I am currently developing a web application by my own and learning at the same time Angular 4 (v4.3) and its Material Design components (alpha). Through my learning process I am facing to many problems (see Translate Angular 4 with ngx-translate and multiple modules) and trying to write down some stories to explain how to do/use some technologies/components.

In this story, I am going to explain how to create a responsive sidenav using the material sidenav similar to the Sidenav developed by Google in their Material components documentation. It will be able to be set with a mode=side on larger screens and mode=over or push on smaller screens regarding to a default size you have set.

This GIF shows when transition from mode=”side” to mode=”over” like on a mobile device

First we hare building our sidenav-container as below (simply copy paste it on your component.html file) :

<md-sidenav-container>
<md-sidenav #sidenav [opened]="screenWidth > 840" [mode]="(screenWidth > 840) ? 'side' : 'over'">
<div class="sidenav-header">
<a routerLink="/"><h5>Hello world!</h5></a>
</div>
</md-sidenav>

<div [ngStyle]="{'display' : (screenWidth > 840) ? 'none' : 'block'}">
<button type="button" md-button (click)="sidenav.open()">
Toggle sidenav when display is block
</button>
</div>

<router-outlet></router-outlet>

</md-sidenav-container>

In order to have a responsive behavior, we are going to set the attributes opened and mode dynamically regarding to a component variable that will be automatically updated on window.onresize(). It will allow us to automatically adapt the sidenav to mobile devices by disabling the mode side as recommended by Google.

Your component.ts file will be as simple as below:

screenWidth: number;

constructor() {
// set screenWidth on page load
this.screenWidth = window.innerWidth;
window.onresize = () => {
// set screenWidth on screen size change
this.screenWidth = window.innerWidth;
};
}

You can now enjoy to see a responsive Sidenav changing its mode at a specific size, allowing you to create a nice user interface.

Thanks to Narxx solution on Stackoverflow that helped to to figure it out how to create this effect.

--

--