Angular 2 + Material 2 Toolbar嵌套Sidenav - Sidenav外部的Call toggle按钮

时间:2017-07-30 13:42:58

标签: angular parent-child angular-material2

我有SidenavComponent和ToolbarComponent嵌套

我想在ToolbarComponent里面的SidenavComponent之外调用sidenav.toggle()

sidenav.component.html

 <md-sidenav-container fullscreen>
    <md-sidenav #sidenav mode="side" color="primary">
     <md-toolbar color="primary"><span>Sidenav</span></md-toolbar>
        <button md-button class="sidenav-link" (click)="sidenav.close()">HOME</button>
      </md-sidenav>

      <app-toolbar></app-toolbar>

    </md-sidenav-container>

sidenav.component.ts

import {Component, OnInit, ViewChild} from '@angular/core';
@Component({
  selector: 'app-sidenav',
  templateUrl: './sidenav.component.html',
  styleUrls: ['./sidenav.component.css']
})
export class SidenavComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

toolbar.component.html

<md-toolbar color="primary">
  <button md-button class="toolbar-menu-button"
          (click)="sidenav.toggle()" (click)="isCollapsed = !isCollapsed">
    <md-icon [@iconChange]="isCollapsed">menu</md-icon>
  </button>
  <span class="toolbar-spacer"></span>
  <button md-button class="toolbar-link" >HOME</button>
  <span class="toolbar-spacer"></span>
</md-toolbar>

toolbar.component.ts

import {Component, Input, OnInit, ViewChild} from '@angular/core';
import { trigger, state, style, transition, animate, keyframes } from '@angular/animations';
import {SidenavComponent} from '../sidenav/sidenav.component';

@Component({
  selector: 'app-toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css'],
  animations: [
    trigger('iconChange', [
      state('true',
        style({ transform: 'rotate( -90deg )' })
      ),
      state('false',
        style({ transform: 'rotate( 0deg )' })
      ),
      transition('* => *', animate('.25s'))
    ])
  ]
})
export class ToolbarComponent implements OnInit {
  constructor() { }

  ngOnInit() {
  }

}

如何在工具栏中调用sidenav.toggle()?

2 个答案:

答案 0 :(得分:3)

将引用#sidenav作为Input传递到您的app-toolbar组件。

toolbar.component.ts:

export class ToolbarComponent implements OnInit {

  @Input() sidenav;

}

sidenav.component.html:

<app-toolbar [sidenav]="sidenav"></app-toolbar>

Plunker demo

另外,我建议改变

(click)="sidenav.toggle()" (click)="isCollapsed = !isCollapsed"

(click)="sidenav.toggle(); isCollapsed = !isCollapsed"

您不需要为每个

分别设置click个活动

答案 1 :(得分:0)

如果从模板中删除逻辑,则将其保留为MVC。

使用ViewChild引用sidenav:

类别:

import { ViewChild } from '@angular/core';
....
@ViewChild('sidenav') private sidenav;
...
onClick(){
 this.sidenav.toggle();
 this.collapsed=!this.collapsed;
 //any other action
}

HTML:

 <button md-button class="toolbar-menu-button" (click)="onClick()">