the_critic the_critic - 10 months ago 147
TypeScript Question

Dynamic template "transclusion" in Angular2

I am trying to achieve something like this:
I have a model class called

There is also a factory
, which based on the type of object passed in will create different components:


export interface ComponentFactoryInterface {

static CreateComponent(obj: CommonSuperObject)


export class ComponentFactory {

public static CreateComponent(obj: CommonSuperObject){

if (obj instanceof ObjectTypeA){
return ObjectComponentA()
}else if (obj instanceof ObjectTypeB){
return ObjectComponentB()


In the template I would like to do something like this:


<component *ngFor="#obj in objects">
<!-- insert custom component template here -->

How do I insert the associated components dynamically ?

I could do something like this (not my preferred way of doing it):

<!-- loop over component models -->
<custom-component-a *ngIf="models[i] instanceof ObjectTypeA">
<custom-component-b *ngIf="models[i] instanceof ObjectTypeB">

But this is seems really wrong to me on many levels (I would have to modify this code and the factory code if I add another component type).

Edit - Working Example

constructor(private _contentService: ContentService, private _dcl: DynamicComponentLoader, componentFactory: ComponentFactory, elementRef: ElementRef){

this.someArray = _contentService.someArrayData;
this.someArray.forEach(compData => {
let component = componentFactory.createComponent(compData);
_dcl.loadIntoLocation(component, elementRef, 'componentContainer').then(function(el){
el.instance.compData = compData;




DCL is deprecated since a while. Use ViewContainerRef.createComponent instead. For an example (with Plunker) see Angular 2 dynamic tabs with user-click chosen components


You can use ngSwitch (similar to your own workaround but more concise) or DynamicComponentLoader

See also