如何制作结构指令来包装我的 DOM 的一部分?

Fri*_*iso 4 html dom angular-directive angular angular5

我目前在我的 HTML 中有以下行:

<p> this is my first line </p>
Run Code Online (Sandbox Code Playgroud)

使用包装器指令,我想添加第二个段落并将其包装在一个 div 中,因此它看起来像这样:

<p wrapper> this is my first line </p>
Run Code Online (Sandbox Code Playgroud)

然后指令将添加包装器和第二行,使最终的 HTML 看起来像这样:

<div>
    <p> this is my first line </p>
    <p> this is my second </p>
</div>
Run Code Online (Sandbox Code Playgroud)

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

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

Fri*_*iso 7

我制定了这样的指令:

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
    }
}
Run Code Online (Sandbox Code Playgroud)