从 mat-sidenav-container 外部的按钮打开 mat-sidenav

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

我尝试对 Angular Material 团队在 this example 上所做的移动使用做同样的事情。

所以我创建了我的组件,如下所示:

<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>

所以调用 sidenav 切换动作的按钮在 mat-sidenav-container 之外,就像在 stackblitz 上的例子一样...... 但是当我点击按钮时出现以下错误:

Cannot read property 'toggle' of undefined

所以按钮打不开侧边导航...

有没有人有办法解决这个问题?

(对不起我的英语,它不是我的母语)

使用opened 输入。 API: https://material.angular.io/components/sidenav/api

模板:

<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>

记得在组件中定义 opened 属性。