How can I make a structural directive to wrap part

2019-04-14 03:26发布

I currently have the following line in my HTML:

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

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>

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>

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.

I'm using Angular 5 in this project.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-14 03:43

I made the directive like so:

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
    }
}
查看更多
Anthone
3楼-- · 2019-04-14 03:55

the templateRef has property called "elementRef" you can throw it access the native dom like this:

this.templateRef.elementRef.nativeElement

So you can get the access to your element like above and use the built in Renderer class providing by angular.

check the below link please

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

查看更多
登录 后发表回答