Angular Material如何在组件方法内关闭MatSidenav而非通过HTML实现
解决方法
你报错的核心原因是:仅声明了sidenav属性,但没有将它和模板中的<mat-sidenav>组件实例做关联,所以运行时该属性没有被赋值,自然为undefined,按照以下步骤配置即可:
步骤1:给侧边栏添加模板引用变量
找到app.component.html中的<mat-sidenav>标签,添加#sidenavRef模板标识,完整结构示例如下:
<mat-sidenav-container> <!-- 新增#sidenavRef作为模板引用标识 --> <mat-sidenav #sidenavRef> <!-- 原有侧边栏内容 --> <mat-list-item *ngIf="isAuth" routerLink="/"> <button mat-icon-button> <mat-icon>logout</mat-icon> <span class="sidenav-span" (click)="onLogoutSideNav()">Logout</span> </button> </mat-list-item> </mat-sidenav> <mat-sidenav-content> <!-- 主页面内容 --> </mat-sidenav-content> </mat-sidenav-container>
步骤2:组件类中用@ViewChild绑定实例
在app.component.ts中先导入必要依赖,再通过@ViewChild装饰器关联模板中的引用变量:
// 顶部导入依赖 import { Component, ViewChild } from '@angular/core'; import { MatSidenav } from '@angular/material/sidenav'; // 你的其他导入,比如AuthService @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // 绑定模板中#sidenavRef对应的MatSidenav实例 @ViewChild('sidenavRef') sidenav!: MatSidenav; // 你的原有变量,比如isAuth等 constructor(private authService: AuthService) {} onLogoutSideNav() { this.authService.logout(); // 此时sidenav已经被正确赋值,可正常调用close方法 this.sidenav.close(); } }
注意事项
如果你的<mat-sidenav>外层有*ngIf条件控制渲染,需要保证调用onLogoutSideNav方法时,侧边栏处于已渲染状态,否则仍然会出现undefined的问题。
内容的提问来源于stack exchange,提问作者Khepf
相关产品推荐
相关产品推荐

