Angular2中如何动态添加克隆节点(相当于cloneNode)

2023-12-07

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

但如何动态添加模板呢?


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

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

选项 1 - 手动将要克隆的元素包装在 a 中<template> tag

这基本上就是您所做的,只是不用打印模板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的行为,所以它可能不是很有用。另外,从你的评论看来yurzui这不是你想要的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular2中如何动态添加克隆节点(相当于cloneNode) 的相关文章