只要路线发生变化,Angular 2 Side-bar就会关闭

时间:2017-05-10 01:52:45

标签: navigation angular2-routing sidebar auto-close

我有一个侧边栏,你可以在外面点击或在栏内的X里面关闭。但是我需要在更改路线时自动关闭(例如从Home到About或Contacts保持打开状态,但我需要它已折叠)

<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。如何通过pkozlowski.opensource

将它用于Angular 2
  

如果您希望每当路线被&gt;成功更改时关闭所有已打开的模态,您可以通过监听&gt;到$ routeChangeSuccess事件在一个中心位置执行此操作,例如在您的应用的运行块中:

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

2 个答案:

答案 0 :(得分:6)

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

@ViewChild('nav') sidenav;

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

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

答案 1 :(得分:-2)

您可以将(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>

希望这有帮助!