Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 4 - i want to create clone of the dom element

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

like image 573
Raj Rana Avatar asked Jan 26 '18 09:01

Raj Rana


2 Answers

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

like image 184
Sachila Ranawaka Avatar answered Sep 21 '22 10:09

Sachila Ranawaka


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

like image 43
santosh singh Avatar answered Sep 20 '22 10:09

santosh singh