每当路线更改时,Angular 2 侧边栏就会关闭

问题描述 投票:0回答:2

我有一个侧边栏,您可以在单击栏中的外部或内部的 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, doesn't collapse

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

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

var myApp = angular.module('app', []).run(function($rootScope, $uibModalStack) {
  $uibModalStack.dismissAll();
}); 
navigation angular2-routing sidebar auto-close
2个回答
16
投票

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

@ViewChild('nav') sidenav;

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

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


-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>
© www.soinside.com 2019 - 2024. All rights reserved.