Alex Lévy
Alex Lévy

Reputation: 653

Angular 2 material : sidenav toggle from component

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

<md-sidenav-layout>
  <md-sidenav #start mode="side" [opened]="true">
      <md-nav-list>
      </md-nav-list>
  </md-sidenav>

  <button md-button (click)="start.toggle()">Close</button>

  <router-outlet></router-outlet>

</md-sidenav-layout>

How to call start.toggle() from my component instead of element with click event?

Thank you for reading

Upvotes: 16

Views: 20806

Answers (4)

Jos&#233; Trindade
Jos&#233; Trindade

Reputation: 43

The simplest way for was to pass the drawer to the component that triggers the toggle.

Html:

<mat-drawer #drawer mode="side">
    ....
</mat-drawer>

<another-component [drawerRef]="drawer"><another-component/>

another-component TS:

export class AnotherComponent implements OnInit {
   @Input() drawerRef: MatDrawer;
   ...
}

another-component HTML:

<button (click)="this.drawerRef.toggle()">

Where another-component is the component that controls the toggle action.

Upvotes: 1

JpCrow
JpCrow

Reputation: 5077

 <md-sidenav #sidenav class="example-sidenav" opened="false">
    <div class="example-sidenav-content">
      <button type="button" md-button (click)="toogleNav(sidenav)">
        toogle
      </button>
    </div>
 </md-sidenav>

And in your ts:

export class AppComponent {

  toogleNav(nav: any) {
    if (nav.opened) {
      nav.close()
    } else {
      nav.open();
    }
  }
}

Upvotes: -1

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

You want to declare a ViewChild in your controller that references the MdSidenav inside your component, like this:

// Sidemenu
@ViewChild('start') sidenav: MdSidenav;

where start is the name of the component you want to reference, in this case the sidenav.

Next you can call methods on that sidenav, like this.sidenav.toggle() inside your controller's functions.

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

Upvotes: 18

Ugnius Malūkas
Ugnius Malūkas

Reputation: 2827

Pass the object to your function.

<md-sidenav-layout>
  <md-sidenav #start mode="side" [opened]="true">
      <md-nav-list>
      </md-nav-list>
  </md-sidenav>

  <button md-button (click)="randomName(start)">Close</button>

  <router-outlet></router-outlet>

</md-sidenav-layout>
import {Component} from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor() {
    }

    randomName(start: any) {
        start.toggle();
    }
}

Upvotes: 11

Related Questions