Automatically close Angular Material Sidenav when menu element is clicked

I’ve recently started digging deeper into Angular Material – the UI kit by Google to be used in Angular projects.

The stack of components available is pretty rich and flexible and includes a variety of things that you can use to quickly scaffold an application, including a Toolbar, Menu, Sidenav, etc.

One thing that I discovered that doesn’t come out of the box is the ability to automatically hide the Sidenav (left side menu) when you click on some of the menu items. Here’s an example structure that I had for a recent project:

The left side is the <mat-sidenav> component and the right side (the table) is wrapped in a <mat-sidenav-content> component. Both of them are wrapped in a <mat-sidenav-container> component.

I wanted to automatically hide the sidebar whenever any of the menu elements: Homepage, Transactions, Accounts, My profile – is being clicked. The solution was pretty simple actually:

<mat-sidenav-container class="example-container">
  <mat-sidenav #sidenav (click)="sidenav.toggle()">
    // My menu is here
    // My main content is here

The trick is to call sidenav.toggle() when a click is triggered on the <mat-sidenav> component.

One thought on “Automatically close Angular Material Sidenav when menu element is clicked

  1. This is great, but if I have the side nav visible on larger screens it disappears when clicked. I need it to only toggle on mobile / smaller screens.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.