在Angular 8中使用ViewChild访问MatDrawer会抛出错误

4
我可以帮您翻译成中文。这段文字是关于在Angular 8版本中,通过组件文件的MatDrawer类型属性来设置MatSideNav行为的。以下是TypeScript代码:
``` 我正在尝试通过组件文件使用MatDrawer类型的属性来设置MatSideNav的行为,在Angular 8版本中实现。 ```
// 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 元素。


1
将 static 设置为 true,或者在模板中添加 *ngIf(文档中提到了这一点,但我记不太清楚了)。 - Francisco Santorelli
@FranciscoSantorelli - 是的,我试过了,它给出了相同的错误。 - B.Balamanigandan
1
很奇怪,这对我来说是有效的 https://stackblitz.com/edit/angular-tyrccg?file=app/sidenav-drawer-overview-example.html - yurzui
@yurzui - 我还是遇到了同样的错误,请稍等,我会尝试在StackBlitz中重现相同的错误。 - B.Balamanigandan
尝试:@ViewChild(MatDrawer) public drawer: MatDrawer - Mehdi Benmoha
显示剩余4条评论
3个回答

5

将声明从以下内容更改为:

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

to

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

1
在我的情况下,问题是因为我没有在我的Angular模块中导入MatSidenavModule。我仍然可以引用MatDrawer而不出错,因为我已经安装了Material,但它不在模块导入列表中。

0

我曾经通过使用@Input装饰器在子组件中传递mat-drawer / sidenav id来解决类似的问题,因此对于OP的问题陈述,可能会像这样解决。

// Declaration
@Input drawerHandler: MatDrawer;

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

在模板中,使用属性绑定将此输入ID值传递。
<mat-drawer-container>
      <mat-drawer #drawer [drawerHandler]="drawer">
        <div>Side nav bar content</div>
      </mat-drawer>
      <div>Main content</div>
</mat-drawer-container>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接