2 Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef
3 } from '@angular/core';
8 export class DynamicComponentService {
10 constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
12 //Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
13 //To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
14 public createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<T> {
16 viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
17 viewContainerRef.clear();
19 let factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
20 let componentRef: ComponentRef<T> = viewContainerRef.createComponent(factory);
25 private getRootViewContainerRef(): ViewContainerRef {
26 return this.applicationRef.components[0].instance.viewContainerRef;