I am developing an Angular app that uses Material UI, I used the Angular CLI to generate the following code:
Navigation HTML
<mat-sidenav-container class="sidenav-container">
<mat-sidenav #drawer class="sidenav" fixedInViewport [attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
[mode]="(isHandset$ | async) ? 'over' : 'side'" [opened]="(isHandset$ | async) === false">
<mat-toolbar>
<mat-icon>keyboard_arrow_down</mat-icon> Select
</mat-toolbar>
<mat-nav-list>
<a mat-list-item [routerLink]="['home']">
<mat-icon>location_on</mat-icon> - Home
</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button type="button" aria-label="Toggle sidenav" mat-icon-button (click)="drawer.toggle()"
*ngIf="isHandset$ | async">
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
</mat-toolbar>
<!-- Add Content Here -->
<ng-content></ng-content>
</mat-sidenav-content>
</mat-sidenav-container>
Navigation TypeScript
import { Component } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent {
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
My problem is that I want the navbar to close (disappear) when the user clicks on a link. How do I do that? When the user clicks a link, the navbar stays enabled. I have to tap somewhere at the background to make it vanish.
you already have a template reference #drawer of the sidenav component so you can call toggle method like this
<mat-nav-list (click)="drawer.toggle()">
<a mat-list-item [routerLink]="['home']">
<mat-icon>location_on</mat-icon> - Home
</a>
</mat-nav-list>
in case we want to toggle the sidebar base of small screen (mobile)
compoenent
toggle(nav: MatSidenav) {
const isSmallScreen = this.breakpointObserver.isMatched(
"(max-width: 599px)"
);
if (isSmallScreen) {
nav.toggle();
}
}
template
<mat-nav-list (click)="toggle(drawer)">
<a mat-list-item [routerLink]="['home']">
<mat-icon>location_on</mat-icon> - Home
</a>
</mat-nav-list>
demo 🚀
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With