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
  </mat-sidenav>
  <mat-sidenav-content>
    // My main content is here
  </mat-sidenav-content>
</mat-sidenav-container>

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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