如何制作结构指令来包装我的 DOM 的一部分? [英] How can I make a structural directive to wrap part of my DOM?
问题描述
我的 HTML 中目前有以下行:
这是我的第一行 </p>
使用包装器指令,我想添加第二个段落并将其包装在 div 中,使其看起来像这样:
这是我的第一行 </p>
然后指令将添加包装器和第二行,使最终的 HTML 看起来像这样:
<p>这是我的第一行 </p><p>这是我的第二个 </p>
根据我对 angular.io 的理解,我需要创建一个结构指令并使用 TemplateRef 和 ViewContainerRef,但我找不到有关如何使用它们来包装 dom 的现有部分并添加第二行的示例.
我在这个项目中使用了 Angular 5.
我是这样制定指令的:
import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';@指示({选择器:'[包装器]'})导出类 WrapperDirective 实现 OnInit {构造函数(私有元素引用:元素引用,私有渲染器:Renderer2) {控制台日志(这个);}ngOnInit(): 无效 {//这将创建包装divconst div = this.renderer.createElement('div');//这将创建第二行const line2 = this.renderer.createElement('p');const text = this.renderer.createText('这是我的第二个');this.renderer.appendChild(line2, text);const el = this.elementRef.nativeElement;//这是要包装的元素const parent = el.parentNode;//这是包含el的父级this.renderer.insertBefore(parent, div, el);//这里我们把div放在el之前this.renderer.appendChild(div, el);//这里我们把el放在div中this.renderer.appendChild(div, line2);//这里我们在 div 中添加第二行,在 el 之后}}
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.
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
}
}
这篇关于如何制作结构指令来包装我的 DOM 的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!