代码之家  ›  专栏  ›  技术社区  ›  Friso

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

  •  5
  • Friso  · 技术社区  · 8 年前

    我当前的HTML中有以下行:

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

    使用wrapper指令,我想添加第二段并将其包装在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。

    2 回复  |  直到 8 年前
        1
  •  9
  •   Friso    8 年前

    我的指示是这样的:

    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
        }
    }
    
        2
  •  1
  •   Nour    8 年前

    templateRef有一个名为“elementRef”的属性,您可以将其抛出以访问本机dom,如下所示:

    this.templateRef.elementRef.nativeElement
    

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

    请检查以下链接

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

    推荐文章