最简单的解决方案是close()
在点击处理程序中使用该函数:
<a [routerLink]="[ 'viewprofile' ]" (click)="sidenav.close()">View Profile</a>
如果适合您,您甚至可以在 sidenav 级别处理收盘:
<mat-sidenav #sidenav [mode]="mode" [opened]="openSidenav" (click)="sidenav.close()">
更复杂的方法是订阅包含 sidenav 的组件中的路由器事件,并根据导航关闭它:
import { Component, ViewChild } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
@Component({
selector: 'my-app',
template: `
<mat-sidenav-container>
<mat-sidenav #sidenav [mode]="mode" [opened]="openSidenav">
<ul class="card-body">
<li><a [routerLink]="[ 'viewprofile' ]">View Profile</a></li>
<li><a [routerLink]="[ 'editprofile' ]">Edit Profile</a></li>
</ul>
</mat-sidenav>
<mat-sidenav-content>
<router-outlet></router-outlet>
</mat-sidenav-content>
</mat-sidenav-container>
`
})
export class AppComponent {
@ViewChild('sidenav') sidenav;
navStart: Observable<NavigationStart>;
constructor(private router: Router) {
// Create a new Observable that publishes only the NavigationStart event
this.navStart = router.events.pipe(
filter(evt => evt instanceof NavigationStart)
) as Observable<NavigationStart>;
this.navStart.subscribe(nav => {
this.sidenav.close();
});
}
}