Angular Renderer2 is recommended to manipulate DOM programatically.
In my directive i take some el.nativeElement.innerText
, transform this text and want to add it to my element:
const text = renderer.createText(`${el.innerText}%`);
renderer.appendChild(el, text);
The problem is with el
- it already has the text, so it appends transformed text after it.
I checked Renderer2 docs and it seems I can use removeChild()
without passing reference to child, so I can't use Renderer2 to clear component first?
In this case only way to achieve it is using innerText = ''
before renderer methods, which makes it pointless.
Maybe something like:
const childElements = this.el.nativeElement.children;
for (let child of childElements) {
this.renderer.removeChild(this.el.nativeElement, child);
}
This is the right code:
const childElements = this.el.nativeElement.childNodes;
for (let child of childElements) {
this.renderer.removeChild(this.el.nativeElement, child);
}
Here is another option using the while loop. As long as there exists a child in the first position, the children will be removed from the end of the collection.
const myEl = this.el.nativeElement;
while(myEl.firstChild) {
this.renderer.removeChild(myEl, myEl.lastChild);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With