2017-02-16 20 views
2

我有一個模態窗口組件,並且我通過<ng-content></ng-content>插入模態內容組件並進行了包含轉換。我需要從模態組件中調用模態內容中的函數。在這種情況下,它將重置模態內容的狀態。我如何獲得對我的模態內容的引用,以便我可以調用它的一個函數?還是有更好的方式與我的孩子內容組件溝通?已插入組件的Angular 2調用函數(ng-content)

更新:我transcluding不同的組件,所以我需要一種方式來獲得參考,而不知道被transcluded內容是什麼類型。

我已經嘗試了幾種找到的解決方法,而且我沒有任何運氣。如果有人可以提供一個plunkr,那會幫助很多。

+1

'@ContentChild()'應該做你想要什麼樣的HTTP ://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-theplate/35209681#35209681 –

+1

還有一些相關的信息在這裏:https://github.com/angular/angular/issues/12758 – BBaysinger

回答

0

Chrispy的評論是正確的。 「...您可以將#templateRef添加到包含它的transcluded組件(即不在ng內容中),然後您可以將其用作選擇器。」

所以我在我的父(莫代爾)成分:

@ContentChild('transcludedContent') private transcludedContent: ModalContent; 

然後在那裏進行模態在我把有:

<modal> 
    <transcluded-component #transcludedContent> 
    </transcluded-component> 
</modal> 
1

你應該可以使用ContentChild修飾器來訪問它。

家長:

import {ChildComponent} from "../child-path"; 

export class ParentComponent { 
    @ContentChild(ChildComponent) childComponent: childComponent; 
    var parentVar = "data"; 

    ... 

    ngAfterViewInit(){ 
     childComponent.callYourFunction(parentVar); 
    } 
} 

更新:請注意,我本來 「ViewChild」 - 這裏的原始鏈接。

更多,請參閱: http://learnangular2.com/viewChild/

編輯:

見岡特的評論 - 他是正確的,ViewChild不會在這種情況下工作。 ContentChild將是一個類似但正確的答案。

https://angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html

編輯2:

有關問題的NG-內容類型,看起來也許你可以這樣做:

在家長:

<parent-component> 
    <child-component #child></child-component> 
</parent-component> 


@ContentChild('child') contentChild: ChildComponent 
+1

在這種情況下,它應該是'@ContentChild()'。 '@ViewChild()'是直接添加到'ParentComponent'模板的組件。 –

+0

@ViewChild(ChildComponent)只有在你知道ChildComponent是被變換的類時纔有效。對我來說,這不會工作,因爲我傳遞不同的組件。如果這些類每個子類都有一個超類,它也不起作用。 – BBaysinger

+0

看到這個討論https://github.com/angular/angular/issues/12758 – BBaysinger

相關問題