Closing md-sidenav when router link is selected

血红的双手。 提交于 2019-12-23 22:11:18

问题


I am working on an angular project, I've implemented angular material components like the side-nav. The side-nav has ul li elements, where the links are nested and are router links not href. my question when I select a link to go to another view, I want to make a call to side nav to toggle and close. cause it always remains open


回答1:


Option 1:

You can subscribe to Router events and close sidenav whenever router event takes place.

Code:

requires these imports:

import { Component,ViewChild, OnInit, } from '@angular/core';
import { Router, RouterModule } from '@angular/router';
import { MdSidenav, MdSidenavModule } from '@angular/material';

in component class:

@ViewChild(MdSidenav) sidenav: MdSidenav;

  title = 'Tour of Heroes';

  constructor(private appService: AppService, 
              private _router: Router){
  }

  ngOnInit() {
    this._router.events.subscribe(() => {
      this.sidenav.close();
    });
}

demo

Option 2:

Add a click event to each li to close sidenav on click.

html:

<ul class="sidenav">
  <li class="sidenav__list">
    <a class="sidenav__list__link " (click)="sidenav.close()" >about</a>
  </li>
</ul>

demo 2



来源:https://stackoverflow.com/questions/45615414/closing-md-sidenav-when-router-link-is-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!