Home > Net >  Angular Material: How to close MatSidenav from inside a method in the component instead of from the
Angular Material: How to close MatSidenav from inside a method in the component instead of from the

Time:11-20

Using Angular Angular Material 12

If you want to close the MatSidenav, then almost every solution I have found says to: (click)="sidenav.close()" in the html component.

But I need that (click) for my logout function (click)="onLogoutSideNav()"

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

I need to close MatSidenav from inside a method in the component instead of from the html. The only solution I could find says to:

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

But doing so returns undefined for this.sidenav.

There are a ton of solutions to use @ViewChild, but I haven't split my navs into header and sidebar components. I'm keeping it simple, doing so from within the 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>

What am I missing here?

CodePudding user response:

you can call multiple functions on click event. eg =>

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

hope this answers your question.

  • Related