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