【问题标题】:angular 4 - i want to create clone of the dom element角度 4 - 我想创建 dom 元素的克隆
【发布时间】:2019-03-02 21:21:56
【问题描述】:

我想创建一个 dom 元素的克隆,例如:-

<div>
  <p></p>
  <p></p>
  <p></p>
  <p></p> 
<button (click)="copy()"></button>
</div>

当我点击按钮时,应该克隆整个 div 元素 在它下面

如果你点击 10 次 10 克隆应该出现 也应该出现原始 dom 元素

我尝试过使用 ng-template 、elementrefrence 、render2 、Viewchild

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    使用创建一个数组并通过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

    【讨论】:

    • 我想在整个页面加载完成后克隆一个dom元素
    【解决方案2】:

    希望下面的代码sn-p对你有帮助:

    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

    【讨论】:

    • 是的,类似这样,但 ng-template 中的元素也应该出现在第一位
    • 默认情况下,整个 div 应该首先出现,然后单击按钮克隆应该出现
    • 是的,但不是我想要的我的 div 应该首先出现,然后它的克隆应该出现在这个演示中发生的事情是每次点击 div 和克隆都同时出现
    • constructor(private resolver:ComponentFactoryResolver){} 是做什么的?
    【解决方案3】:

    我知道可能为时已晚,但您可以这样做:

    import {Component, ElementRef, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      @ViewChild('viewContainer', {read: ViewContainerRef}) viewContainer: ViewContainerRef;
      @ViewChild('template') template: TemplateRef<any>;
    
      insertView() {
        const template = this.template.createEmbeddedView(null);
        this.viewContainer.insert(template);
      }
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      相关资源
      最近更新 更多