How to make a responsive nav-bar using Angular material 2?

kero picture kero · Jul 5, 2016 · Viewed 65.1k times · Source

I'm trying to create a navigation bar using Angular material 2 that collapses in small screens like mobile devices and tablets.

I was only able to find md-button but not md-menu-bar as was in Angular material.

Answer

user2662006 picture user2662006 · Jan 26, 2017

Here is what I used to build my responsive nav-bar using Angular2+ Material 2 and flex-layout in angular-cli app.

(Please visit Install Angular Material and Angular CDK)

1) Install flex-layout

npm install @angular/flex-layout -save

2) Include flex-layout in your app.module.ts

import {FlexLayoutModule} from "@angular/flex-layout";

3) Import

imports: [
 BrowserModule,
 FormsModule,
 HttpModule,
 RoutingModule,
 FlexLayoutModule,
MyOwnCustomMaterialModule // Please visit the link above "Install Angular Material and Angular CDK", and check (Step 3: Import the component modules).
],

app.component.html

<mat-toolbar color="primary">

    <button mat-button routerLink="/">
    <mat-icon>home</mat-icon> 
        {{title}}</button>

    <!-- This fills the remaining space of the current row -->
    <span class="fill-remaining-space"></span>
    <div fxLayout="row" fxShow="false" fxShow.gt-sm>
        <button mat-button routerLink="/products">Products</button>
        <button mat-button routerLink="/dashboard">Dashboard</button>
    </div>
    <button mat-button [mat-menu-trigger-for]="menu" fxHide="false" fxHide.gt-sm>
     <mat-icon>menu</mat-icon>
    </button>

</mat-toolbar>
<mat-menu x-position="before" #menu="matMenu">
    <button mat-menu-item routerLink="/products">Products</button>
    <button mat-menu-item routerLink="/dashboard">Dashboard</button>
    <!--<button mat-menu-item>Help</button>-->
</mat-menu>

app.component.css

.fill-remaining-space {
   /*This fills the remaining space, by using flexbox.  
  Every toolbar row uses a flexbox row layout. */
  flex: 1 1 auto;
}

Note: to test, resize your page.

take a look at flex-layout docs