How can I insert a new child as the first child of a parent using Angular 2' Renderer2?
Given <div> <span>Foobar</span> </div>
I want to insert an element before the span
so it becomes <div> <span>New element</span> <span>Foobar</span> </div>
.
Problem is that I only have access to the containing div and I cannot figure out how to either 'prepend' the new element (as jQuery can/would do it), or find the first child element of the parent so that I can use insertBefore
from the renderer.
I tried using ContentChild
to get the first element, but it gives null
, and I guess that it because this is all going on in a directive and I don't know the content of the native element.
Usage is this; a directive that adds an icon tag as the first child of an element, eg <button myIconDirective>Foobar</button>
should become <button myIconDirective><i class="icon-classes"></i>Foobar</button>
.
Here's a plunker to tinker with, the +'s are currently at the wrong side of the text :) http://plnkr.co/edit/mknH3yeTnFpepaIwmHUN
It doesn't seem to be possible without falling back on using native node firstChild
child reference:
ngAfterViewInit() {
const newElement = this.renderer.createElement('i');
this.renderer.insertBefore(this.el.nativeElement, newElement, this.el.nativeElement.firstChild);
}
And the plunker
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