2016-11-22 24 views
2

我想知道是否有可能在按鈕上點擊複製父組件的html語法內的子組件模板?如何在父級內部點擊複製子組件模板? (angular2)

所以;

<child-component></child-component> 

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span> 

那麼一旦用戶點擊 '+' glyphicon和onDuplicate()函數被調用,,父有:

<child-component></child-component> 
<child-component></child-component> 

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span> 

等等等等

我一直在四處尋找對於如何做這樣的事情,但找不到任何東西,所以我不知道從哪裏開始。我希望有人能夠指引我正確的方向?

感謝

回答

3

可以在父模板中使用ngFor在你的父組件定義的屬性。

//父及部件

public childItems: any[] = []; 

public onDuplicate(){ 
    this.childItems.push(this.childItems.length); 
} 

//父模板

<child-component *ngFor="let child of childItems"></child-component> 

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span> 
1

一個想法是有一個包裹裏面*ngFor子組件,然後對類實現的計數器。點擊然後會增加計數器(實際上是源數組)。是這樣的:

<div *ngFor="let cc of childrenCounter"> 
    <children-component></children-component> 
</div> 

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span> 

利用具有類:

private childrenCounter: number[] = []; 

private onDuplicate(): void { 
    this.childrenCounter.push(0); // just add any element 
} 

該數組是難看溶液代替一個簡單的計數器,但至今it is necessary

0

在一個* ngFor指令和你的函數中調用onDuplicate()遞增循環變量(如果你有自定義對象只是將你的對象推入數組)。

相關問題