renderer2 append child node after parent node

2.5k views Asked by At

I want to append new child node after the parent node but appendChild appends it inside of it. Here is what I have:

My component.html:

<div id="parent" (click)="appendChild()">
    parent node
</div>

My component.ts:

private appendChild() {
    const div = this.renderer.createElement('div');
    const text = this.renderer.createText('child node')
    this.renderer.appendChild(div, text);
    this.renderer.appendChild(document.getElementById("parent"), div)
}

This inserts new div that was created inside of parent node like this:

enter image description here

but how do I append it outside of parent node? Like this:enter image description here

1

There are 1 answers

0
Andrei On BEST ANSWER

just insert it in elements parent

private appendChild() {
    const div = this.renderer.createElement('div');
    const text = this.renderer.createText('child node')
    this.renderer.appendChild(div, text);
    const parent = document.getElementById("parent")
    this.renderer.insertBefore(parent.parentElement, div, this.renderer.nextSibling(parent))
}