2

I'm wondering if it would be possible on a button click to duplicate the child component template inside the parent's html syntax?

So;

<child-component></child-component>

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

then once the user clicks the '+' glyphicon and the onDuplicate() function is called,, the parent has:

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

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

etc etc.

I have been looking around for ways to do something like this but can't find anything so I'm not sure where to start. I was hoping someone could point me in the right direction?

Thanks

confusedandenthused
  • 201
  • 2
  • 3
  • 10

3 Answers3

3

You can use ngFor in parent template with property defined in your parent component.

// parent componet

public childItems: any[] = [];

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

// parent template

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

<span class="glyphicon glyphicon-plus" (click)="onDuplicate()"></span>
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
1

One idea is to have children components wrapped inside an *ngFor, then have a counter on the class implementation. The click would then increment the counter (the source array, actually). Something like this:

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

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

With the class having:

private childrenCounter: number[] = [];

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

The array is an ugly solution instead of a simple counter, but so far it is necessary.

Community
  • 1
  • 1
rodrigocfd
  • 6,450
  • 6
  • 34
  • 68
0

Pur your in a *ngFor directive and in your function onDuplicate() increment the loop variabile (if you have custom object just push your object into the array).

M. Guertz
  • 1
  • 2