3

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

*什么会起作用,来自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;
} 

但是如何动态添加模板呢?

4

1 回答 1

7

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

<p>Paragraph One</p>
<p>Paragraph Two</p>   <!-- Let's try to clone this guy -->
<p>Paragraph Three</p>

选项 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);
    }
}

在此示例中,我将“克隆”插入到标记 ( <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>

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

<p>Paragraph One</p>
<p *clone>Paragraph Two</p>
<p>Paragraph Three</p>

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

这基本上会复制*ngFor's 的行为,所以它可能不是很有用。此外,从您的评论看来yurzui,这不是您想要的。

于 2017-01-29T13:38:56.947 回答