Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Renderer2 prependChild-like behavior

Tags:

angular

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

like image 943
altschuler Avatar asked Aug 10 '17 22:08

altschuler


1 Answers

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

like image 171
Max Koretskyi Avatar answered Oct 17 '22 07:10

Max Koretskyi