Angular Material:使用mat-sidenav,无法读取未定义的属性“ toggle”

时间:2019-06-18 00:53:17

标签: html css angular angular-material angular8

我有一个带有Angular Material 8的Angular 8项目,该项目无法通过同一组件中的按钮切换sidenav。 javascript控制台说

  

无法读取未定义的属性“ toggle”

,但是sidenav在模板中具有引用变量。

我已经确保按钮在模板中,这样我就不必担心事件发射器或其他诡计。这应该很简单。

HTML

<mat-toolbar color="primary">
  <button mat-icon-button (click)="sidenav.toggle()" *ngIf="(isHandset$ | async)"><mat-icon>menu</mat-icon></button>
  <span>This Be Me App, Matey</span>
</mat-toolbar>
<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #sidenav class="sidenav" fixedInViewport="true" *ngIf="isAuthenticated()"
      [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
      [mode]="(isHandset$ | async) ? 'over' : 'side'"
      [opened]="(isHandset$ | async) ? 'false' : 'true'">
    <mat-toolbar><mat-icon (click)="sidenav.toggle()" *ngIf="(isHandset$ | async)">arrow_back</mat-icon> Menu</mat-toolbar>
    <mat-nav-list>
      <a mat-list-item [routerLink]="['/home']" routerLinkActive="active">Home</a>
      <a mat-list-item (click)="logout()">Logout</a>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content class="content">    
    <!-- Add Content Here -->
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>

菜单按钮出现并在断点处消失,如预期的那样,但是单击它会出现错误。

应该发生的是,该按钮仅在您到达isHandset$中断以下(发生)时才出现,然后应在内容的顶部打开(不会发生)。由于#sidenav参考变量位于mat-sidenav标记中,看来我已经正确设置了它。

1 个答案:

答案 0 :(得分:2)

您共享的错误必须具有依赖性或缺少某些内容;要查看工作方式,我们必须解决您代码中的2个*ngIf条件:

  • isAuthenticated()-可能是错误的,我们不知道您使用的逻辑
  • (isHandset$ | async)-我们不知道可观察的逻辑

假设这2个*ngIf条件为真,则代码可以正常工作...'无法读取未定义的属性'toggle'的错误”

相关的 ts

import {Component} from '@angular/core';

@Component({
  selector: 'sidenav-open-close-example',
  templateUrl: 'sidenav-open-close-example.html',
  styleUrls: ['sidenav-open-close-example.css'],
})
export class SidenavOpenCloseExample {
  events: string[] = [];
  opened: boolean;
  isHandset$:boolean =true;
  isAuthenticated(){ return true;}

  shouldRun = [/(^|\.)plnkr\.co$/, /(^|\.)stackblitz\.io$/].some(h => h.test(window.location.host));
}

您可以检查working stackblitz here