Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Dynamically add component after n-th child

Is there an elegant way I can implement the following solution in angular 2?

<div id="parent">
    <div>Child 1</div>
    <div>Child 2</div>
    <div>Child 3</div>
</div>

$("#parent > div:nth-child(2)").after("<div>foobar</div>");

I started liked this, but it is adding foobar after Child 1. I want it after Child 2.

Dynamically insertion Plnkr

like image 939
Jey Avatar asked Dec 12 '25 00:12

Jey


1 Answers

Instead of using ViewChild, you can use ViewChildren to append the child component to last div. ViewChildren will view target div's children using QueryList

@ViewChildren('target', {read: ViewContainerRef}) target: QueryList(ViewContainerRef);

And need to grab last div like this,

this.cmpRef = this.target._results[2].createComponent(factory)  
//<---added ._results[2] which returns last div element.
//<---you can use ._result[0],_resultt[1],_result[2] to append dynamic component accordingly.

Working Demo : https://plnkr.co/edit/1KOK8gYgJnzAMUGnyy1P?p=preview

Note: Now, you can make it more dynamic if you want.


UPDATE

As _results is a private member of QueryList use the following to prevent tslint errors.

this.cmpRef = this.target.toArray()[index].createComponent(factory);
like image 200
Nikhil Shah Avatar answered Dec 16 '25 00:12

Nikhil Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!