我想创建一个dom元素的克隆,例如: -
<div>
<p></p>
<p></p>
<p></p>
<p></p>
<button (click)="copy()"></button>
</div>
这里当我点击按钮时,应该克隆整个div元素 在它下面
如果您单击10次,则应出现10个克隆 也应该出现orignal dom元素
我尝试过ng-template,elementrefrence,render2,Viewchild
答案 0 :(得分:4)
希望以下代码段可以帮助您:
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 强>
答案 1 :(得分:2)
使用创建数组并通过<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)
}
SELECT a.assetnum,
MAX(a.description) AS description,
MAX(a.user) AS user,
MAX(b.invdate) as invdate,
(SELECT i.note FROM inventory i
WHERE i.invdate = MAX(b.invdate) AND i.assetnum=a.assetnum) note
FROM asset a
LEFT JOIN inventory b on a.assetnum=b.assetnum
GROUP BY a.assetnum
答案 2 :(得分:1)
我知道可能为时已晚,但是您可以这样做:
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);
}
}
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);
}
}