Reputation: 994
I need to auto close Material Sidebar right after navigation by clicking on Sidebar nav items. but it seems it isn't working naturally in that way. I'm creating Stackblitz for my issue:
Stackblitz Editor Site: https://stackblitz.com/github/adnanebrahimi/MaterialSidebarIssue
HTML:
<mat-sidenav #drawer class="sidenav" fixedInViewport
[attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
[mode]="(isHandset$ | async) ? 'over' : 'side'"
[opened]="(isHandset$ | async) ? 'false' : 'true'">
Component:
export class SidebarLayoutComponent {
isHandset$: Observable<boolean> =
this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches)
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
We have isHandset$
as Observable to determine that the device is handset or not by this feature we just open it if it's false and close it if it's true to be a handset.
But I want also to close the sidebar when we start navigating on other pages.
Thank you.
Upvotes: 0
Views: 1567
Reputation: 994
I manage it by this code:
export class SidebarLayoutComponent {
isHandset = false;
isHandset$: Observable<boolean> =
this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => {
if (result.matches) {
this.isHandset = true;
return true;
} else {
this.isHandset = false;
return false;
}
})
);
@ViewChild('drawer', { static: true }) drawer: MatDrawerContainer;
constructor(private breakpointObserver: BreakpointObserver, private router: Router)
{
this.router.events.pipe(filter(event => event instanceof NavigationStart))
.subscribe((event: NavigationStart) => {
if (this.isHandset) {
this.drawer.close();
console.log('closed');
}
});
}
}
Upvotes: 0
Reputation: 598
Try to use the same toggle function (click)="drawer.toggle()"
used on hamburger icon in sideNav in all your sideNav links
HTML:
<mat-nav-list>
<a mat-list-item [routerLink]="['/page-one']" routerLinkActive="router-link-active"
(click)="drawer.toggle()">Page One</a>
<a mat-list-item [routerLink]="['/page-two']" routerLinkActive="router-link-active" (click)="drawer.toggle()">Page Two</a>
<a mat-list-item [routerLink]="['/page-eager']" routerLinkActive="router-link-active" (click)="drawer.toggle()">Page Eager</a>
</mat-nav-list>
Upvotes: 1