本文介绍了如何制作结构性指令以包装我的DOM的一部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前在HTML中包含以下行:

I currently have the following line in my HTML:

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

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

Using a wrapper directive I want to add a second paragraph and wrap it in a div so it will look like this:

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

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

And then the directive will add the wrapper and second line to make the final HTML look like this:

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

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

From what I understand from angular.io I will need to create a structural directive and use a TemplateRef and a ViewContainerRef, but I can't find an example on how to use them to wrap an existing part of the dom and add a second line.

我在此项目中使用的是Angular 5.

I'm using Angular 5 in this project.

推荐答案

我发出的指令如下:

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

这篇关于如何制作结构性指令以包装我的DOM的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:07