Html 如何生成一个结构化指令来包装DOM的一部分?

Html 如何生成一个结构化指令来包装DOM的一部分?,html,angular,dom,angular-directive,angular5,Html,Angular,Dom,Angular Directive,Angular5,我当前的HTML中有以下行: <p> this is my first line </p> 这是我的第一行 使用wrapper指令,我想添加第二段,并将其包装在div中,使其看起来像这样: <p wrapper> this is my first line </p> <div> <p> this is my first line </p> <p> this is my secon

我当前的HTML中有以下行:

<p> this is my first line </p>
这是我的第一行

使用wrapper指令,我想添加第二段,并将其包装在div中,使其看起来像这样:

<p wrapper> this is my first line </p>
<div>
    <p> this is my first line </p>
    <p> this is my second </p>
</div>
this.templateRef.elementRef.nativeElement
这是我的第一行

然后该指令将添加包装器和第二行,以使最终的HTML如下所示:

<p wrapper> this is my first line </p>
<div>
    <p> this is my first line </p>
    <p> this is my second </p>
</div>
this.templateRef.elementRef.nativeElement

这是我的第一行

这是我的第二次

从我的理解来看,我需要创建一个structural指令,并使用TemplateRef和ViewContainerRef,但我找不到一个如何使用它们包装dom的现有部分并添加第二行的示例


我在这个项目中使用Angular 5。

templateRef有一个名为“elementRef”的属性,您可以像这样将它抛出以访问本机dom:

<p wrapper> this is my first line </p>
<div>
    <p> this is my first line </p>
    <p> this is my second </p>
</div>
this.templateRef.elementRef.nativeElement
因此,您可以像上面那样访问元素,并使用angular提供的内置渲染器类

请检查下面的链接


我是这样做的:

import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';

@Directive({
    selector: '[wrapper]'
})
export class WrapperDirective implements OnInit {

    constructor(
        private elementRef: ElementRef,
        private renderer: Renderer2) {
        console.log(this);
    }

    ngOnInit(): void {
        //this creates the wrapping div
        const div = this.renderer.createElement('div');

        //this creates the second line
        const line2 = this.renderer.createElement('p');
        const text = this.renderer.createText('this is my second');
        this.renderer.appendChild(line2, text);

        const el = this.elementRef.nativeElement; //this is the element to wrap
        const parent = el.parentNode; //this is the parent containing el
        this.renderer.insertBefore(parent, div, el); //here we place div before el

        this.renderer.appendChild(div, el); //here we place el in div
        this.renderer.appendChild(div, line2); //here we append the second line in div, after el
    }
}