单击导航项后无法自动关闭“材质”侧边栏

时间:2019-06-24 13:21:34

标签: angular angular-material

导航后,我需要通过单击补充工具栏导航项来自动关闭“材料补充工具栏”。但似乎不是以这种方式自然地工作。 我正在为我的问题创建Stackblitz:

Stackblitz编辑器站点: 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'">

组件:

export class SidebarLayoutComponent {

  isHandset$: Observable<boolean> = 
  this.breakpointObserver.observe(Breakpoints.Handset)
   .pipe(
         map(result => result.matches)
        );

  constructor(private breakpointObserver: BreakpointObserver) {}

}

通过isHandset$可以观察到该设备是否为手持设备,如果此功能为假,则仅将其打开,如果为真,则将其关闭。 但是,当我们开始在其他页面上浏览时,我也想关闭侧边栏。

谢谢。

2 个答案:

答案 0 :(得分:1)

尝试在所有sideNav链接中使用与sideNav中的汉堡图标相同的切换功能(click)="drawer.toggle()"

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>

Stackblitz demo

答案 1 :(得分:0)

我通过以下代码对其进行管理:

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');
      }
    });

 }

}