建议使用Angular Renderer2以编程方式操作DOM。
在我的指令中,我采取一些el.nativeElement.innerText
,转换此文本,并希望将其添加到我的元素:
const text = renderer.createText(`${el.innerText}%`);
renderer.appendChild(el, text);
问题出在el
上 - 它已经有了文本,所以它会在它之后附加转换后的文本。
我检查了Renderer2文档,似乎我可以使用removeChild()
而不传递对child的引用,所以我不能先使用Renderer2来清除组件?
在这种情况下,实现它的唯一方法是在渲染器方法之前使用innerText = ''
,这使得它毫无意义。
也许是这样的:
const childElements = this.el.nativeElement.children;
for (let child of childElements) {
this.renderer.removeChild(this.el.nativeElement, child);
}
这是正确的代码:
const childElements = this.el.nativeElement.childNodes;
for (let child of childElements) {
this.renderer.removeChild(this.el.nativeElement, child);
}