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

6k Views Asked by At

I'm trying to change the icon of mat-icon depending on close or open mat-sidenav but unable to find if sidenav is open or close below is my code

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

here is the toggle button

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

  @ViewChild(MatSidenav)
  sidenav!: MatSidenav;
2

There are 2 best solutions below

0
Chellappan வ On BEST ANSWER

mat-sidenav component have opened input property we can use that to check whether sidenav open or not

   <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>
0
danday74 On

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

From the docs:

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.

Here's a stackblitz with all the code you'll ever need:

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

In this stackblitz they are using the latter approach to bind to the opened property of the component. The opened property is a boolean, controlling whether the sidenav is opened (true) or closed (false).

Alternatively, if you prefer the former approach (which it seems you are currently using) then just do:

@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 
  })
}

Your html would look like this:

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