navigationangular2-routingsidebarauto-close

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


I have a sidebar which you can close when clicking outside or on X inside in bar. But I need to have auto close when changing routes (for example from Home to About or Contacts stays open, but I need that it collapses)

<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

I find something that looks like what I need possible but it's for AngularJs. How can I use it for 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();
}); 

Solution

  • you can add (click)="nav.close()" to all your links that will be very easy way of achieving it,

     <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>