Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear element from all children in Angular (5+) Renderer2?

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.

like image 322
Łukasz Ostrowski Avatar asked May 10 '18 16:05

Łukasz Ostrowski


3 Answers

Maybe something like:

const childElements = this.el.nativeElement.children;
for (let child of childElements) {
  this.renderer.removeChild(this.el.nativeElement, child);
}
like image 59
J.J Avatar answered Oct 17 '22 11:10

J.J


This is the right code:


    const childElements = this.el.nativeElement.childNodes;
    for (let child of childElements) {
      this.renderer.removeChild(this.el.nativeElement, child);
    }

like image 31
palex01 Avatar answered Oct 17 '22 12:10

palex01


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);
}
like image 43
patelb Avatar answered Oct 17 '22 11:10

patelb