如何在angular2中动态添加克隆的节点(等同于cloneNode)

GWo*_*ing 2 dom clonenode ng-template angular

在Angular2中,在某些情况下,我需要复制节点而不是移动它。该节点具有angular2属性,因此cloneNode不起作用。我该怎么做?

*什么不起作用

    let el = <HTMLElement>document.getElementById(divId);
    if ((<HTMLElement>el.parentNode).id == 'itsMe')
        el = <HTMLElement>el.cloneNode(true);
    document.getElementById(anotherId).appendChild(el);
Run Code Online (Sandbox Code Playgroud)

*什么工作有效,来自Angular2:克隆组件/ HTML元素及其功能

@Component({
  selector: 'my-app',
  template: `
    <template #temp>
        <h1 [ngStyle]="{background: 'green'}">Test</h1>
        <p *ngIf="bla">Im not visible</p>   
    </template>
    <template [ngTemplateOutlet]="temp"></template>
    <template [ngTemplateOutlet]="temp"></template>
    `
})

export class AppComponent {
    bla: boolean = false;
    @ContentChild('temp') testEl: any;
} 
Run Code Online (Sandbox Code Playgroud)

但是如何动态添加模板?

Ang*_*hef 5

让我们使用以下标记进行说明:

<p>Paragraph One</p>
<p>Paragraph Two</p>   <!-- Let's try to clone this guy -->
<p>Paragraph Three</p>
Run Code Online (Sandbox Code Playgroud)

选项1-手动包装元素以在<template>标签内克隆

基本上,这就是您所做的事情,只是不要打印出模板ngTemplateOutlet,而是在组件的类中获取对它的引用,然后使用强制将其插入createEmbeddedView()

@Component({
    selector: 'my-app',
    template: `
      <p>Paragraph One</p>
      <template #clone>
        <p>Paragraph Two</p>
      </template>
      <p>Paragraph Three</p>

      <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)

在此示例中,我将“克隆”插入标记(<div #container></div>)中的特定位置,但您也可以将其附加在当前组件模板的底部。

另请注意,原件<p>Paragraph Two</p>不再可见。

选项2-使用结构指令

如果要在元素的当前位置克隆元素则以:

<p>Paragraph One</p>
<p>Paragraph Two</p>   <!-- Original paragraph -->
<p>Paragraph Two</p>   <!-- Cloned paragraph   -->
<p>Paragraph Three</p>
Run Code Online (Sandbox Code Playgroud)

然后,您可以创建一个结构指令*clone并将其应用于要克隆的段落,如下所示:

<p>Paragraph One</p>
<p *clone>Paragraph Two</p>
<p>Paragraph Three</p>
Run Code Online (Sandbox Code Playgroud)

有趣的是,结构指令的作用是将其应用于<template>标签中的元素包装起来。与选项1中的操作非常相似,只是在这种情况下,我们无法控制克隆的打印位置(它们将出现在原始段落的位置)。

这实质上将复制*ngFor的行为,因此它可能不是很有用。另外,从您的评论看来yurzui,这不是您想要的。