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

Raj*_*ana 6 typescript angular

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>
Run Code Online (Sandbox Code Playgroud)

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

Sac*_*aka 5

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)
  }
Run Code Online (Sandbox Code Playgroud)

demo


san*_*ngh 5

希望以下代码片段对您有所帮助:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

演示

  • `constructor(private resolver:ComponentFactoryResolver){}` 的作用是什么? (2认同)