Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 236
Alex Lévy Avatar asked Oct 12 '16 12:10

Alex Lévy


2 Answers

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

like image 96
Alexander Ciesielski Avatar answered Oct 10 '22 13:10

Alexander Ciesielski


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();
    }
}
like image 27
Ugnius Malūkas Avatar answered Oct 10 '22 12:10

Ugnius Malūkas