Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 material: sidenav toggle from another component

I'm using Angular 2 Material sidenav in my project this way:

app.component.ts (Main) html view:

<md-sidenav-layout>
  <md-sidenav #start mode="side" [opened]="true">
      This is the main sidenav
      <sidebar></sidebar>
  </md-sidenav>

  <md-sidenav #end align="end">
    This sidenav suppose to open from different components across my application to show extra information/data when user clicks an image for example.
    <br>
    <button md-button (click)="end.close()">Close</button>
  </md-sidenav>

<router-outlet></router-outlet>

</md-sidenav-layout>

Now.. in order to open the #end sidenav I use the following button in the same component:

<button md-button (click)="end.open()">Open End Side</button>

But, what if I want to use end.open() from a different component to toggle the sidenav? How I am supposed to make the sidenav "gloal" so I can open it on any component in my app?

like image 274
TheUnreal Avatar asked May 09 '16 13:05

TheUnreal


People also ask

How do you toggle Sidenav?

Opening and closing a sidenav A <mat-sidenav> can be opened or closed using the open() , close() and toggle() methods.

How do you fix Sidenav mats?

For <mat-sidenav> only (not <mat-drawer> ) fixed positioning is supported. It can be enabled by setting the fixedInViewport property. Additionally, top and bottom space can be set via the fixedTopGap and fixedBottomGap. These properties accept a pixel value amount of space to add at the top or bottom.


1 Answers

Usually a shared service is used for this.

Provide the service at a common ancestor. The component that controls the open status injects the service and the components that want to request the controlling component to change the status also inject the service.

When some component wants the sidenav to toggle, they send an event using the shared service. The component controlling the toggle listens for events and toggles on request.

For more details see https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

like image 94
Günter Zöchbauer Avatar answered Sep 30 '22 01:09

Günter Zöchbauer