2015-12-11 10 views
1

我有一個父組件和一個子組件。我希望能夠從父組件上的某個方法調用子組件上的某個子方法。 有沒有辦法獲得對父類的子組件實例的引用並調用子公共方法?對子組件執行方法

@Component({ 
    selector: 'child-component' 
}) 
@View({ 
    template: `<div>child</div>` 
}) 
class ChildComponent{ 
    constructor() { 

    } 

    doChildEvent() { 
     // some child event 
    } 
} 

@Component({ 
    selector: 'parent-component' 
}) 
@View({ 
    template: ` 
     <child-component #child></child-component> 
    `, 
    directives: [ 
     ChildComponent 
    ] 
}) 
class ParentComponent { 
    private child:ChildComponent; 

    constructor() { 

    } 

    onSomeParentEvent() { 
     this.child.doChildEvent(); 
    } 
} 

我試着把一個哈希放在模板中的孩子,並在類中引用它,但沒有成功。

+0

'#child' - 這些本地模板變量不會成爲組件上的屬性(如您發現的那樣)。我在關於它們範圍的文檔中找不到任何東西(我不想看源代碼)。看來它們的範圍僅限於模板。 –

回答

5

這是ViewChild是:

//don't forget to import ViewChild 

class ParentComponent { 
    @ViewChild(ChildComponent) private child:ChildComponent; 

    constructor() { 
     //this.child is undefined because constructor is called before AfterViewInit 
    } 

    onSomeParentEvent() { 
     //this.child contains the reference you're looking for 
     this.child.doChildEvent(); 
    } 
} 

假設onSomeParentEventAfterViewInit之後觸發, this.child將包含子組件的引用。

+0

正是我在找的! – Sagi