2017-05-25 58 views
2

我的應用程序中有一個材料2 sidenav組件。我如何從我的課程訪問組件方法?在我的情況下,我想調用open()方法。在模板與<button md-button (click)="sidenav.open()">完全正常工作,但如果我通過this.el.nativeElement.open();使用的方法在課堂上,它拋出:來自類的調用組件的方法

ERROR TypeError: Cannot read property 'open' of undefined

我的組件:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core'; 

@Component({ 
    selector: 'app-sidebar-content', 
    template: ` 
    <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> 
    `, 
    styleUrls: ['./sidebar-content.component.css'] 
}) 
export class SidebarContentComponent implements OnInit { 

    @ViewChild('sidenav') el: ElementRef; 

    constructor() { } 

    ngOnInit() { 

    } 

    openSideNav() { 
    // this.el.nativeElement.open(); 
    // ERROR TypeError: Cannot read property 'open' of undefined 
    } 

} 

回答

3

我認爲你濫用ViewChild。 查看ViewChild的官方文檔:https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

ViewChild獲取要跟蹤的組件的類類型。在你的情況下,它是MdSidenav我想。 你應該改變你的代碼如下,以便能夠訪問你的模板注入的第一批sidenav組件:

export class SidebarContentComponent implements OnInit { 

    @ViewChild(MdSidenav) sidenav: MdSidenav; 

    constructor() { } 

    ngOnInit() { 

    } 

    openSideNav() { 
    this.sidenav.open(); 
    } 

} 
1

更改@ViewChild像這樣:

@ViewChild('sidenav', {read: ComponentRef}) c: ComponentRef;

然後你就可以訪問像這樣的實例方法。

c.instance.open()

編輯:

您也可以直接指定類型像對方回答您的組件類型說...