Angular 2 material : sidenav toggle from component

拥有回忆 提交于 2020-01-22 07:08:07

问题


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


回答1:


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




回答2:


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();
    }
}



回答3:


 <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();
    }
  }
}


来源:https://stackoverflow.com/questions/39998157/angular-2-material-sidenav-toggle-from-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!