[Fixed] How to toggle angular material sidenav in component

Issue

How to call angular material sidenav actions in component? I have use case that sidenav only can open / close when callMethods() method triggered. I can’t simply pass open(e) in callMethods() as well (required 1 arugument). Is there anyway to achieve this?

app.html

<mat-sidenav-container class="example-container">
  <mat-sidenav #sidenav [mode]="mode.value">
    <p>
      some nav here
    </p>
  </mat-sidenav>

  <mat-sidenav-content>
    <p><button mat-button (click)="open(sidenav)">Toggle</button></p>
    <p>
      some text here
    </p>
  </mat-sidenav-content>
</mat-sidenav-container>

app.ts

open(e: any) {
    e.toggle();
  }

  callMethods() {
    this.open(); // required 1 arguments
    this.otherMethod();
  }
anotherMethod() {
    this.open(); // required 1 arguments
    this.otherMethod();
  }

Note: I noticed there is a post but not clear

Solution

A nice clean way of opening and closing the angular material side-nav goes through the [opened] parameter on the component. You can pass it a boolean that you can manipulate to open/close the side-nav.

app.html

<mat-sidenav-container class="example-container">
  <mat-sidenav #sidenav [mode]="mode.value" [opened]="isShowing">
    <p>
      some nav here
    </p>
  </mat-sidenav>

  <mat-sidenav-content>
    <p><button mat-button (click)="toggleSidenav()">Toggle</button></p>
    <p>
      some text here
    </p>
  </mat-sidenav-content>
</mat-sidenav-container>

Your callMethods functions can then cleanly call your toggle method if it’s implemented as follows:

app.ts

isShowing: boolean;

toggleSidenav() {
   this.isShowing = !this.isShowing;
}

callMethods() {
    this.toggleSidenav();
}

 

Leave a Reply

(*) Required, Your email will not be published