i want to create a clone of the dom element for eg:-
<div>
<p></p>
<p></p>
<p></p>
<p></p>
<button (click)="copy()"></button>
</div>
here when i click on the button the whole div element should be cloned below it
if you click 10 times 10 clone should appear also the orignal dom element should appear
i have tried with the ng-template ,elementrefrence ,render2 ,Viewchild
use create an array and loop it through ngFor
<div *ngFor="let item of items">
<p>{{item}}</p>
</div>
<button (click)="copy()"> copy</button>
items: number[] = [1,2,3];
copy() {
this.items.push(this.items.length + 1)
}
demo
Hope following code snippet help you:
import { Component,ViewChild,ViewContainerRef,ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div>
<ng-template #clone>
<p>lorem</p>
<p></p>
<p></p>
<p></p>
<p></p>
</ng-template>
</div>
<button (click)="cloneTemplate()">Clone Template</button>
<div #container></div>
`
})
export class AppComponent{
// What to clone
@ViewChild('clone') template;
// Where to insert the cloned content
@ViewChild('container', {read:ViewContainerRef}) container;
constructor(private resolver:ComponentFactoryResolver){}
cloneTemplate(){
this.container.createEmbeddedView(this.template);
}
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With