user user - 2 months ago 15
TypeScript Question

How to define place where dynamic components would be injected?

My components injected dynamical. But how to define place where they would be without any wrapping?

import { Component, ViewContainerRef, ComponentResolver } from '@angular/core';

constructor(
private apiService: ApiService,
private viewContainerRef: ViewContainerRef,
private componentResolver: ComponentResolver) {
}

create() {
this.componentResolver.resolveComponent(PieChart).then((factory) => {
this.viewContainerRef.createComponent(factory);
});
}


And i want to inject them in some DIV.

<div class="someClass">
<!--How inject them here? -->
</div>

Answer

There are two ways:

  • injecting the ViewContainerRef like in your question, then new components are added below this component

  • using a target element in your components template with a template variable like <div #target></div> and @ViewChild('target', {read: ViewContainerRef}) viewContainerRef:ViewContainerRef; to get the ViewContainerRef of this <div>. Added elements are again added below this <div>

createComponent() allows to pass an index. By default new components are always added at the end, but if you pass an index it is inserted at this position.
(not tested) with index 0 you should be able to add the new element before the target element.
If you add more than one component to the same ViewContainerRef you can pass an index to insert the new component before the elements added earlier.