如何在 angular 中检查 mat-sidenav 是否打开或关闭?

How to check if mat-sidenav is open or close in angular?

我正在尝试根据关闭或打开 mat-sidenav 更改 mat-icon 的图标,但无法找到 sidenav 是否打开或关闭下面是我的代码

<mat-sidenav appResponsiveMenu mode="side" opened>
        my menu items list
</mat-sidenav>

这是切换按钮

<button mat-icon-button (click)="sidenav.toggle()">
   <mat-icon *ngIf="sidenav">keyboard_arrow_left</mat-icon>
   <mat-icon *ngIf="!sidenav">keyboard_arrow_right</mat-icon>
</button>

.ts代码

  @ViewChild(MatSidenav)
  sidenav!: MatSidenav;

https://material.angular.io/components/sidenav/overview#opening-and-closing-a-sidenav

来自文档:

A mat-sidenav can be opened or closed using the open(), close() and toggle() methods. Each of these methods returns a Promise that will be resolved with true when the sidenav finishes opening or false when it finishes closing.

The opened state can also be set via a property binding in the template using the opened property. The property supports 2-way binding.

这是一个堆栈闪电战,其中包含您需要的所有代码:

https://stackblitz.com/angular/xxbbxnybjov?file=src%2Fapp%2Fsidenav-open-close-example.ts

在这个 stackblitz 中,他们使用后一种方法绑定到打开的 属性 组件。 opened属性是一个boolean,控制sidenav是打开(true)还是关闭(false)。

或者,如果您更喜欢前一种方法(您目前似乎正在使用这种方法),那么只需执行以下操作:

@ViewChild(MatSidenav)
sidenav!: MatSidenav;

sidenavIsOpen = false

openSideNav() {
  this.sidenav.open().then((sidenavIsOpen: boolean) => {
    this.sidenavIsOpen = sidenavIsOpen 
  })
}

closeSideNav() {
  this.sidenav.close().then((sidenavIsOpen: boolean) => {
    this.sidenavIsOpen = sidenavIsOpen 
  })
}

toggleSideNav() {
  this.sidenav.toggle().then((sidenavIsOpen: boolean) => {
    this.sidenavIsOpen = sidenavIsOpen 
  })
}

您的 html 看起来像这样:

<button mat-icon-button (click)="toggleSideNav()">
  <mat-icon *ngIf="sidenavIsOpen">keyboard_arrow_left</mat-icon>
  <mat-icon *ngIf="!sidenavIsOpen">keyboard_arrow_right</mat-icon>
</button>

mat-sidenav组件已经打开输入属性我们可以用它来检查sidenav是否打开

   <button mat-icon-button (click)="sidenav.toggle()">
       <mat-icon *ngIf="sidenav.opened">keyboard_arrow_left</mat-icon>
       <mat-icon *ngIf="!sidenav.opened">keyboard_arrow_right</mat-icon>
    </button>