Angular 2 路线改变时关闭侧边栏

Angular 2 Side-bar to be closed whenever a route is changed

我有一个侧边栏,您可以在点击栏外或点击栏内的 X 时将其关闭。但是我需要在更改路线时自动关闭(例如从主页到关于或联系人保持打开状态,但我需要它折叠)

<md-toolbar class='toolbar' color="primary" >

  <button md-icon-button (click)="nav.open()">
    <md-icon class="md-24">menu</md-icon>
  </button>


</md-toolbar>

<md-sidenav-container>

  <md-sidenav #nav>
        <md-nav-list>
  <button md-icon-button (click)="nav.close()">
    <md-icon class="md-24">close</md-icon>
  </button>
      <a md-list-item routerLink='home'class="active"> Home </a>

      <a md-list-item routerLink='about' class= "page-scroll" > About us</a> 
    <a md-list-item routerLink='discount' class= "page-scroll" >Discounts </a>
    <a md-list-item routerLink='contact'class= "page-scroll" >Contact </a>
       <a md-list-item routerLink='order' class= "page-scroll" >Order</a>...


    .md-toolbar {
padding-top: 1em;
align-self: flex-start;
height:5em;


}


.toolbar{

  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  width: 100%;
  height: 50px;


}


md-nav-list{
     margin-left: 20px;
  margin-right: 10px;
    margin-top: 80px;
      font-size: 1.2em;
      font-family: Raleway;
}



@media screen and (max-width: 600px) {
  .logo {

display: none  }
  .search{

  }
}


html {
  height: 100%;
}
body {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

.container{
    margin-top: 100px;
        margin-bottom: 100px;
  flex: 1 0 auto;

}

When I choose another tab the background is still black and sidebar is opened, don't collapse

我找到了一些看起来像我可能需要的东西,但它适用于 AngularJs。我如何将它用于 Angular 2 by pkozlowski.opensource

If you want all the opened modals to be closed whenever a route is >changed successfully, you could do it in one central place by listening >to the $routeChangeSuccess event, for example in a run block of your app:

var myApp = angular.module('app', []).run(function($rootScope, $uibModalStack) {
  $uibModalStack.dismissAll();
}); 

您可以将 (click)="nav.close()" 添加到您的所有链接,这将是实现它的非常简单的方法,

 <a md-list-item (click)="nav.close()" routerLink='home'class="active"> Home </a>
 <a md-list-item (click)="nav.close()" routerLink='about' class= "page-scroll" > About us</a> 
 <a md-list-item (click)="nav.close()" routerLink='discount' class= "page-scroll" >Discounts </a>
 <a md-list-item (click)="nav.close()" routerLink='contact'class= "page-scroll" >Contact </a>
 <a md-list-item (click)="nav.close()" routerLink='order' class= "page-scroll" >Order</a>

更简单的解决方案可能是监听路由器事件。

@ViewChild('nav') sidenav;

constructor(private router: Router) {
  router.events.subscribe((val) => {
    if (val instanceof NavigationEnd) {
      this.sidenav.close();
    }
  });
}

这样您就不必为每个 link 添加点击事件。