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

How can I make a structural directive to wrap part of my DOM?

目前我的 HTML 中有以下行:

<p> this is my first line </p>

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

<p wrapper> this is my first line </p>

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

<div>
    <p> this is my first line </p>
    <p> this is my second </p>
</div>

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

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

templateRef 有 属性 调用 "elementRef" 你可以像这样让它访问本机 dom:

this.templateRef.elementRef.nativeElement

因此您可以像上面那样访问您的元素并使用 angular 提供的内置渲染器 class。

请检查以下link

https://angular.io/api/core/Renderer2

我的指令是这样的:

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