如何通过单击具有RouterLink的元素仅在移动设备上起作用来关闭Material SideNav

时间:2019-07-11 06:20:34

标签: angular8 angular-material-7

我将角钢8与角钢材料结合使用。我正在使用有角度的材料Sidenav路由器和自定义菜单:`

<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>`

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是在点击处理程序中使用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();
    });
  }
}