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

标签 html angular dom angular-directive angular5

目前我的 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。

最佳答案

我的指令是这样的:

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

关于html - 如何制作结构指令来包装我的 DOM 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499234/

相关文章:

jQuery 移动用户代理检测

javascript - 如何使变量成为可调用函数?

javascript - 当两个包管理器查看相同的 package.json 文件时,为什么我的新 Angular-Fire 设置在 pnpm 中被破坏并在 npm 中工作?

node.js - 在更改 Node 中的变量/模型时,Angular 2 不会更新 UI

angular - 当你运行 ng serve 时会发生什么?

html - 将另一个背景图像添加到已有内嵌背景图像的元素中

javascript - jquery 处理由 jinja (django) 加载的 html5 元素的问题

JavaScript 在 DOM 中移动元素

php - 在 PHP 中获取 DomElement 的内部 HTML

javascript - jQuery 如果列表项包含 '' -".remove()?