2017-05-31 74 views
1

我已經開始學習Angular2和Material設計。我想創建一個具有以下組件的應用程序。見下圖供參考Angular2中的可重用Sidenav材質設計

  1. 漢堡菜單按鈕。點擊它將顯示側面板
  2. 側面板。它會有其他幾個選項。此菜單是通用於所有應用程序的屏幕

enter image description here

我已經創建了3個組成部分的圖像中可見。右鍵菜單component.html看起來如下

<md-sidenav #sidenav mode="side" class="app-sidenav"> 
    <ul> 
    <li>Menu Item</li> 
    <li>Menu Item</li> 
    <li>Menu Item</li> 
    <li>Menu Item</li> 
    <li>Menu Item</li> 
    <li>Menu Item</li> 
    </ul> 
</md-sidenav> 

我想知道我怎麼揭示輕按按鈕此菜單,無論是從主屏幕或約屏幕

中的例子在docs顯示在單一頁面的執行,而不是作爲一個可重複使用的菜單組件

編輯1: 我不希望放置該按鈕根頁上的一些畫面,如登錄,註冊等不會有菜單。但是,如果將它們放在根頁面上是一種更好的方法,並且可以顯示/隱藏該按鈕,那麼我會添加它。

編輯2: 我嘗試在Angular文檔中使用示例而不更改任何代碼行。

<md-sidenav-container class="example-container"> 
    <md-sidenav #sidenav class="example-sidenav"> 
    Jolly good! 
    </md-sidenav> 

    <div class="example-sidenav-content"> 
    <button md-button (click)="sidenav.open()"> 
     Open sidenav 
    </button> 
    </div> 

</md-sidenav-container> 

當我點擊 「打開sidenav」 按鈕,它提供了以下錯誤控制檯

EXCEPTION: Error in ./HomeComponent class HomeComponent - inline template:34:4 caused by: self._el_42.open is not a function 

編輯3: 下面是模塊的版本

angular-cli: 1.0.0-beta.28.3 
node: 6.9.5 
os: darwin x64 
@angular/animations: 4.1.3 
@angular/common: 2.4.10 
@angular/compiler: 2.4.10 
@angular/core: 2.4.10 
@angular/forms: 2.4.10 
@angular/http: 2.4.10 
@angular/material: 2.0.0-beta.3 
@angular/platform-browser: 2.4.10 
@angular/platform-browser-dynamic: 2.4.10 
@angular/router: 3.4.10 
@angular/compiler-cli: 2.4.10 
+0

顯而易見的解決辦法是把根頁面上的按鈕和側欄和使用<路由器出口>改變一切 – elasticrash

+0

@elasticrash:請閱讀編輯。另外,你可以分享一些調用/顯示右側菜單(sidenav)的代碼 – Sahil

+0

還有其他一些更復雜的方法來達到這個目的,比如動態地將一個組件注入到一個視圖中......例如通過一個路徑守衛。這是非常相似的這種方法https://stackoverflow.com/questions/41602522/dynamically-load-different-css-files-in-angular2-application-based-on-users-lan/44111038#44111038 – elasticrash

回答

0

創建一個處理sidenav和工具欄之間連接的服務。

sidenav.service.ts

@Injectable() 
export class SidenavService { 
    toggle = new EventEmitter(); 

    constructor() { 
    } 
} 

toolbar.component.ts

export class ToolbarComponent implements OnInit { 

    constructor(public sidenavService: SidenavService) { } 
} 

toolbar.component.html

<md-toolbar color="primary" fxLayout="row" color="none"> 
    <button ... (click)="sidenavService.toggle.emit()"> ... </button> 
</md-toolbar> 

sidenav.component.ts

@ViewChild('sidenav') sidenav: MdSidenav; 

constructor(private sidenavService: SidenavService) { 

    this.sidenavService.toggle 
     .asObservable() 
     .subscribe(
     () => this.sidenav.toggle() 
     ); 
} 

sidenav.component。HTML

<md-sidenav #sidenav>...</md-sidenav> 
+0

我試過了你描述的方式。單擊該按鈕會在sidenav.component.ts中發出錯誤「sidenav.toggle不是函數」。 console.log(sidenav)打印「ElementRef {nativeElement:md-sidenav.app-sidenav}」 – Sahil

+0

我再次測試過它,但對我來說它工作正常。你能告訴我更多關於你的問題嗎?或者您正在使用哪種版本的材料 –

+0

我在編輯3中添加了版本 – Sahil