The Angular materials sidenav can be toggled open using a hamburger button on the nav menu. However, when the side menu comes out there is no X button to close it. You have to "click off of it" to close it.
I would like to place a button on the sidenav that will toggle it closed.
The toggle function is in the header component, not the sidenav child component. So how do I "reach" the toggle function in the header component FROM within the sidenav component?
header.component.html:
<mat-drawer-container class="header" [hasBackdrop]="false">
<mat-drawer #drawer mode="side" position="end" class="drawer">
<app-sidemenu (sidenav)="toggle($event)"></app-sidemenu> // The sidenav
</mat-drawer>
<mat-drawer-content>
<mat-toolbar color="primary" class="toolbar">
<span class="title-text" (click)="open('/home')">My Website Title</span>
<app-navmenu></app-navmenu>
<button // The hamburger button to toggle sidenav open close
mat-icon-button
class="toolbar-item"
(click)="toggleDrawer()"
>
<mat-icon id="drawerButton">menu</mat-icon>
</button>
</mat-toolbar>
</mat-drawer-content>
header.component.ts :
export class HeaderComponent {
constructor() {}
@ViewChild('drawer', { static: false }) drawer!: MatDrawer;
toggle(action: string) {
if (action === 'toggle') {
this.drawer.toggle(); // toggle the sidenav open/closed.
}
}
}
sidenav.component.html:
<div class="menu" id="sideNavDrawer" #sideNavDrawer>
<div class="menu-header">
<div class="logout">
<button
mat-icon-button
class="toolbar-item"
(click)="toggle()" // How to toggle sidenav closed ???
>
<mat-icon id="drawerButton">cancel</mat-icon>
</button>
<div class="menu-item" (click)="open('products/manage')">
<span>Menu Link 1</span>
</div>
<div class="menu-item">
<span>Menu Link 2</span>
</div>
</div>
So in the sidenav.component.ts file, how do I get that toggle button in sidenav to talk to the toggle() function in the header and close the drawer?
I can't seem to refence the drawer itself from within sidenav?
Thanks!
the easy way to achieve toggling drawer from another component is creating service and inject it in the header this is a working example : stackblitz