Search code examples
angularangular-materialangular6angular-routing

Closing side-nav on clicking router link for small devices


I am using side-nav component in my project for routing between the components,which looks like this:

enter image description here

Here i am facing an issue.The side-nav appears as toggle-menu for mobile devices as shown in the image. When i click/select any list-item (ex Home) .The side-nav should close.But it is not.

I have asked it once, still no appropriate solution.

Here is the stackblitz DEMO


Solution

  • You can do this by

    • providing a reference to mat-sidenav as <mat-sidenav #snav
    • Using this reference to toggle or close the mat-sidenav, from where you want this side nav to close. Say, from an anchor click as
      <a mat-list-item routerLink="." *ngFor="let nav of fillerNav" (click)="snav.toggle()" >
    • You can use (click)="snav.toggle()" or (click)="snav.close()"

    Code :

    <mat-sidenav #snav [mode]="mobileQuery.matches ? 'over' : 'side'" 
    [fixedInViewport]="mobileQuery.matches" fixedTopGap="56">
          <mat-nav-list>
            <a mat-list-item routerLink="." *ngFor="let nav of fillerNav" 
              (click)="snav.toggle()" >{{nav}}</a>
          </mat-nav-list>
        </mat-sidenav>
    

    Stackblitz Demo showing closing of side nav on clicking on item-link

    Application Code : https://stackblitz.com/edit/angular-close-side-nav-on-button-click?file=app%2Fsidenav-responsive-example.html


    Update 1 :