2017-10-19 92 views
0

我試圖多次調用組件HTML,但不包括父組件中的子組件。多次實例化一個@ViewChild,所以我可以再次使用HTML Angular 4

我需要它是這樣的:

<father-component> 
    <child-component #id> 
    <button (click) = "#id.show()"> 
</father-component> 

在子組件的HTML是隱藏的,直到我按下按鈕。

事情是,我想顯示的孩子組件的HTML多次按下按鈕。

據我所知,@ViewChild只實例化一次html,所以如果我嘗試追加到另一個div的HTML,它會追加相同的。我需要知道是否有辦法在任何時候調用一個新的@ViewChild實例。

+0

ViewChild只是對DOM元素的引用。也許你想使用ViewChildren? – rjustin

+0

'@ViewChild()'與實例化HTML無關,它僅提供對視圖中元素,組件或指令的訪問。另見https://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/35209681#35209681 –

回答

3

一個可能的解決方案是使用一種ngFor這樣的:

<father-component> 
    <child-component *ngFor="let i of children"> 
    <button (click) = "increment()"> 
</father-component> 

然後在你的組件類的increment方法是增加孩子的數量。這將允許你有任何數量的子組件。

相關問題