使用ViewChild访问MatDrawer在Angular 8中引发错误

时间:2019-06-03 12:15:48

标签: angular angular-material viewchild mat-sidenav mat-drawer

我正在尝试使用Angular版本8中的MatDrawer类型的属性通过组件文件设置MatSideNav的行为

TypeScript代码:

// Declaration
@ViewChild('drawer', { static: false }) public drawer: MatDrawer;

// Toggle the Side Nav bar
showSideNav(): void {
    this.drawer.toggle();
}

HTML代码:

<mat-drawer-container>
      <mat-drawer #drawer>
        <div>Side nav bar content</div>
      </mat-drawer>
      <div>Main content</div>
</mat-drawer-container>

控制台错误:

ERROR TypeError: "this.drawer is undefined"

请协助我如何使用MatDrawer访问@ViewChild元素

1 个答案:

答案 0 :(得分:1)

更改声明来自

@ViewChild('drawer', { static: false }) public drawer: MatDrawer;

@ViewChild('drawer', { static: true }) public drawer!: MatDrawer;