【问题标题】:Access MatDrawer using ViewChild is throwing error in Angular 8使用 ViewChild 访问 MatDrawer 在 Angular 8 中引发错误
【发布时间】:2019-10-18 23:58:27
【问题描述】:

我正在尝试使用 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"

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

【问题讨论】:

  • 将 static 设置为 true,或在模板中添加 *ngIf(他们在文档中提到了这一点,但我不太记得了)
  • @FranciscoSantorelli - 是的,我试过了,它给出了同样的错误。
  • @yurzui - 我仍然遇到同样的错误,请稍等,我会检查并尝试在 StackBlitz 中重现相同的错误。
  • 试试:@ViewChild(MatDrawer) public drawer: MatDrawer

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


【解决方案1】:

更改声明来自

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

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

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2017-03-03
    • 2020-06-13
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2020-06-02
    • 2020-04-03
    • 1970-01-01
    相关资源
    最近更新 更多