How can I close Material SideNav by clicking on an element which has the RouterLink directive?

angular material sidenav
close sidebar on click outside angular
close sidenav on click outside
mat-drawer backdrop
materialize sidenav close on click
angular material sidenav example
angular material fixed sidenav
toggle sidebar menu from other component in angular 4

I am using angular 4 in combination with angular material.

I am using a sidenav container a router and a custom generated menu:

<mat-sidenav-container>
<mat-sidenav #sidenav>
    <app-menu></app-menu>
</mat-sidenav>
<router-outlet></router-outlet>
</mat-sidenav-container>

Inside the menu component I am using default angular 4 router links:

<ul>
  <li *ngFor="let hero of heroes">
    <a mat-button [routerLink]="['/hero/', hero.id]" queryParamsHandling="merge">
      {{hero.name}}
    </a>
  </li>
</ul>

What I would like to do is to close the Material sidenav when clicking on one of those router links.

I can assure you that without the click event routing works fine, it just does not close my sidenav, because the router-outlet is inside the side navigation.

However, when I add a (click)="sidenav.close()" to the a my full page suddenly refreshed, instead of just following the router link.

I have tried many things, but I can't seem to figure it out, hope someone can help!

I created a service so that the sidenav could be controlled from various components. I followed this example.

Then it's a matter of watching the router for events and closing as needed. In app.component.ts:

this.router.events.subscribe(event => {
  // close sidenav on routing
  this.sidenavService.close();
});

This doesn't work if you want to close the sidenav on only specific links, but the service itself would facilitate that.

How to open & close sidenav on clicking a toggle button using , The toggle button is in Header component and sidenav is different tab without which the side nav wont be visible I wrote a basic directive for the How can I close Material SideNav by clicking on an element which has the RouterLink  You could even handle the close at the sidenav level if that suits you: <mat-sidenav #sidenav [mode]="mode" [opened]="openSidenav" (click)="sidenav.close()"> A more sophisticated approach would be to subscribe to router events in your component that contains the sidenav, and close it based on navigation:

Here's a complete solution based off of Angular Material's schematics generated sidenav layout component. This answer improves on the previous ones by taking into consideration whether we are on a handset device or not, and making sure the sidenav only closes on a handset device.

A few points:

  1. This component was generated by using Angular Materials navigation schematics.
  2. I called my component my-menu however, you may use any other name.
  3. The sidenav will only close if we are not on a handset device, this is done using the rxjs operator withLatestFrom combined with the isHandset$ stream which was generated by the schematics.
import { Component, ViewChild } from '@angular/core';
import { BreakpointObserver, Breakpoints, BreakpointState } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, filter, withLatestFrom } from 'rxjs/operators';
import { Router, NavigationEnd } from '@angular/router';
import { MatSidenav } from '@angular/material';

@Component({
  selector: 'app-my-menu',
  templateUrl: './my-menu.component.html',
  styleUrls: ['./my-menu.component.css']
})
export class MyMenuComponent {
  @ViewChild('drawer') drawer: MatSidenav;

  isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
    .pipe(
      map(result => result.matches)
    );

  constructor(private breakpointObserver: BreakpointObserver,
    router: Router) {
    router.events.pipe(
      withLatestFrom(this.isHandset$),
      filter(([a, b]) => b && a instanceof NavigationEnd)
    ).subscribe(_ => this.drawer.close());
  }
}

Closing the Angular Material Sidenav Post Navigation, “Closing the Angular Material Sidenav Post Navigation” is published by Ole After clicking on Accounts we want our MatSidenav to close. How can I close Material SideNav by clicking on an element which has the RouterLink directive? angular angular-material2 asked Oct 25 '17 at 14:56 stackoverflow.com

Inspired on @isherwood's answer I came up with a solution:

I created the following service:

import { Injectable } from '@angular/core';
import { MatSidenav } from '@angular/material';

@Injectable()
export class SidenavService {

  public sideNav:MatSidenav;
  constructor() { }
}

I changed my app component to set the sideNav property in the above service.

export class AppComponent implements OnInit {
  title = 'app';

  @ViewChild('sidenav') public sideNav:MatSidenav;
  constructor(private sidenavService: SidenavService) {      
  }

  ngOnInit() {
    this.sidenavService.sideNav = this.sideNav;
  }
}

Please note that it's very important to implement OnInit and to set the sidenavService.sideNav in the ngOnInit function.

You can then use your sideNavService anywhere you want. In my case I use it only in the components that I actually link in my side navigation menu.

Example:

 export class HeroComponent implements OnInit {

  constructor(private sidenavService: SidenavService) {      
  }

  ngOnInit() {
    this.sidenavService.sideNav.close();
  }
}

You'll probably want to do it on change of a parameter instead of on init, but you get the point.

sidenav close on click, How can I configure the sidenav to close on click?Sample Blog · Contact · E-​commerce · Features · Intros · Magazine · Projects · Social · Team · Testimonials. Directives. mdbInput · Waves effect I have to add (click)="sidenav.hide()" even if i have routerlinks. But on Clicking on an mdb-item should close the sidenav too. Sidenav in Angular Material. SideNav basically uses 3 components to add sidenav into a full page. They are - <mat-sidenav-container> which acts as a structural container for content and sidenav, <mat-sidenav-content> which represents the main content, and <mat-sidenav> which represents the added side content.Following is a sample sidenav .html

You don't need to make a service for this. This is a simple solution.

<mat-sidenav-container [hasBackdrop]="true">
                <mat-sidenav #sidenav mode="side" class="sideNavigation">
                        <mat-nav-list>
                                <a mat-list-item routerLink="" (click)="sidenav.close()"> bar</a>
                                <a mat-list-item routerLink="/bar" (click)="sidenav.close()">foo</a>
                                <a mat-list-item routerLink="/foo" (click)="sidenav.close()">whatever</a>
                                <a mat-list-item routerLink="/something1" (click)="sidenav.close()">SomePage</a>
                                <a mat-list-item routerLink="/something2" (click)="sidenav.close()">Some Page</a>
                        </mat-nav-list>
                </mat-sidenav>
                <mat-sidenav-content>
                        <mat-toolbar color="accent">
                                <mat-icon (click)="sidenav.toggle()">menu</mat-icon> 
                                <div class="divider"></div>
                                <img class="img" src="../assets/img/logo.png" alt="logo" (click)="goHome()" />
                        </mat-toolbar>
                        <router-outlet></router-outlet>
                </mat-sidenav-content>
        </mat-sidenav-container>

All you do is add (click)="sidenav.close()" along with the routerLink="/whatever/path/here" works. This will close the sidenav on directing to a page.

Close drawer on navigation link click · Issue #1246 · google/material , Component name: Layout / Navigation Drawer Material Design spec URL for the If somebody needs the angular directive to close the drawer on nav link click, here it is : function() { var drawer = angular.element(document. (I had some trouble toggling the sidenav while using [routerLink] :neckbeard: ). Sidenav. Next, let’s take a look at the Sidenav element. Sidenav is part of the Angular Material library and makes it possible to display a panel next or beside some primary content. To demonstrate the usage of Sidenav let’s create a new component first by executing the following command in our project directory: $ ng g component sidenavdemo

I tested another solution in case it is necessary to call a method, it seemed easier and more practical using @ViewChild, I'll leave it here in case anyone wants to.

app.component.html:

<mat-sidenav #snav mode="over" fixedTopGap="56">
  <mat-nav-list class="pt-0">
    <a mat-list-item (click)="closeAllSidenav()">
      Navigation Item
    </a>
  </mat-nav-list>
</mat-sidenav>

app.component.ts:

import { ViewChild } from '@angular/core';
import { MatSidenav } from '@angular/material/sidenav';

@ViewChild('snav', { static: false }) usuarioMenu: MatSidenav;

closeAllSidenav() {
  this.usuarioMenu.close();
}

guide layout with angular material · devonfw/devon4ng Wiki · GitHub, We use the a tags with mat-list-item directive. We implement a click listener on each link to close the sidenav when it is clicked. The routerLink  A basic example of using the RouterLink directive can look like this: The different url segments can also be passed in an array like this: You can go up to higher levels in the navigation using something like this: In that example, if the user is at /red-pill/neo, the navigation will change to /blue-pill/neo.

Angular Material Navigation Menu, The source code is available at GitHub Angular Material Navigation Menu a place for a side navigation and the <mat-sidenav-content> element As you can see, we use the fxHide.gt-xs directive, which states that The click event is there for every link, to close the side-nav as soon as a user clicks on it. ng new angular6-sidenav-example cd angular6-sidenav-example ng add @angular/material ng g c login-layout ng g c home-layout ng g c login ng g c navigation ng g c first ng g c second ng g c toolbar For a clear implementation, I have created a separate file - material.module.ts and imported in our app.module.ts.

Creating UIs with Angular Material Design Components, Angular Material is the implementation of Material Design principles and (​menus, sidenav and toolbar); layout components (grids, cards, tabs and lists ) <​a mat-button routerLink="/customer-create">Create Customer</a> <a native HTML <button> and <a> elements and add Material attributes such as  As I side note I plan on fleshing out my example project(go-material) into a todo or google keep style app so that new people can have a good example. Also remember that its still an early beta and so much has improved even over the last month that I've been using it.

Menu, Navigation keyboard_arrow_up. Menu · Sidenav · Toolbar open_in_new. Menu. By itself, the <mat-menu> element does not render anything. The menu is attached to and opened via application of the matMenuTriggerFor directive: <mat​-menu The menu exposes an API to open/close programmatically. Please note that  dec23rd1986 - which problem did you encounter? Navbar doesn't close after clicking in mobile view? If yes, please add routerLink="/" to every element. Please give me more information. Best Regards, Damian

Comments
  • Will you explain, how it works only for mobile devices
  • Jomal, please ask a new question in a new post. Comments aren't the place for that.
  • Great solution. Technically the component's view is only fully initialised after the lifecycle hook AfterViewInit, but I guess this works because a router event only gets sent after that anyway.
  • this code is difficult to understand, but it works. From angular 8+ you should use @ViewChild('drawer', { static: true }) drawer: MatSidenav;
  • you could define your links property in the ts file as an array and then loop on that array so you don't have to repeat (click)="sidenav.close()"