【问题标题】:Angular Material: How to close MatSidenav from inside a method in the component instead of from the html?Angular Material:如何从组件中的方法内部而不是从 html 关闭 MatSidenav?
【发布时间】:2021-12-30 11:30:38
【问题描述】:

使用 Angular + Angular 材质 12

如果您想关闭 MatSidenav,那么我发现的几乎每个解决方案都说: (click)="sidenav.close()" 在 html 组件中。

但我的注销功能需要(点击)(click)="onLogoutSideNav()"

onLogoutSideNav() {
    this.authService.logout();
  }

我需要从组件中的方法内部而不是从 html 中关闭 MatSidenav。我能找到的唯一解决方案是:

sidenav!: MatSidenav
...
onLogoutSideNav() {
    this.authService.logout();
    this.sidenav.close();
  }

但是这样做会为 this.sidenav 返回 undefined。

使用@ViewChild 的解决方案有很多,但我没有将导航拆分为标题和侧边栏组件。我保持简单,在 app.component 中这样做。

<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>

我在这里错过了什么?

【问题讨论】:

    标签: javascript angular angular-material mat-sidenav


    【解决方案1】:

    您可以在点击事件上调用多个函数。 例如 =>

    (click)="onLogoutSideNav();test()"
    

    希望这能回答你的问题。

    【讨论】:

    • 成功了。 (click)="onLogoutSideNav(); sidenav.close()" 准确地说。我不知道你可以通过(点击)一次调用两个东西,只需用分号分隔它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多