Jomal Johny
Jomal Johny

Reputation: 501

How can I close Material SideNav by clicking on an element which has the RouterLink only works on mobile devices

I am using angular 8 in combination with angular material. I am using an angular material Sidenav a router and a custom menu:`

<mat-sidenav-container>
  <mat-sidenav #sidenav [mode]="mode" [opened]="openSidenav">
    <ul class="card-body">
       <li><a  [routerLink]="[ 'viewprofile' ]">View Profile</a></li>
       <li><a  [routerLink]="[ 'editprofile' ]">Edit Profile</a></li>
   </ul>
 </mat-sidenav>
 <mat-sidenav-content>
  <router-outlet></router-outlet>
 </mat-sidenav-content>
</mat-sidenav-container>`

Upvotes: 0

Views: 99

Answers (1)

G. Tranter
G. Tranter

Reputation: 17928

The simplest solution is to use the close() function in a click handler:

<a [routerLink]="[ 'viewprofile' ]" (click)="sidenav.close()">View Profile</a>

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:

import { Component, ViewChild } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: `
    <mat-sidenav-container>
      <mat-sidenav #sidenav [mode]="mode" [opened]="openSidenav">
        <ul class="card-body">
          <li><a [routerLink]="[ 'viewprofile' ]">View Profile</a></li>
          <li><a [routerLink]="[ 'editprofile' ]">Edit Profile</a></li>
        </ul>
      </mat-sidenav>
      <mat-sidenav-content>
        <router-outlet></router-outlet>
      </mat-sidenav-content>
    </mat-sidenav-container>
  `
})
export class AppComponent {
  @ViewChild('sidenav') sidenav;

  navStart: Observable<NavigationStart>;

  constructor(private router: Router) {
    // Create a new Observable that publishes only the NavigationStart event
    this.navStart = router.events.pipe(
      filter(evt => evt instanceof NavigationStart)
    ) as Observable<NavigationStart>;

    this.navStart.subscribe(nav => {
      this.sidenav.close();
    });
  }
}

Upvotes: 1

Related Questions