angularangular-materialsidenav

Opening mat-sidenav from a button outside of mat-sidenav-container


I try to do the same thing for a mobile usage that Angular Material teams have done on this example.

So I created my component, like this :

<app-component-0></app-component-0>
<div class="d-lg-none">
    <button mat-icon-button (click)="snav.toggle()">
         <mat-icon>menu</mat-icon>
    </button>
    <mat-sidenav-container class="sidenav-container">
        <mat-sidenav #snav mode="over">
           <app-menu-tree>
           </app-menu-tree>
        </mat-sidenav>
        <mat-sidenav-content>
           <router-outlet></router-outlet>
        </mat-sidenav-content>
   </mat-sidenav-container>
</div>
<app-component-1-desktop class="d-none d-lg-flex flex-column"></app-component-1-desktop>

So the button who call the toggle action of the sidenav is outside of the mat-sidenav-container, exactly like in the example on stackblitz... But I have the following error when I click on the button:

Cannot read property 'toggle' of undefined

And so the button can't open the sidenav...

Does anyone have an idea to fix this ?

(Sorry for my english, it is not my native language)


Solution

  • Use the opened input. API: https://material.angular.io/components/sidenav/api

    template:

    <button mat-icon-button (click)="opened = !opened">
      <mat-icon>menu</mat-icon>
    </button>
    <mat-sidenav-container class="example-container">
      <mat-sidenav #sidenav mode="over" [(opened)]="opened">
        <app-menu-tree></app-menu-tree>
      </mat-sidenav>
      <mat-sidenav-content>
        <router-outlet></router-outlet>
      </mat-sidenav-content>
    </mat-sidenav-container>
    

    remember to define the opened property in your component.