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> {
15 viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
16 viewContainerRef.clear();
18 const factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
19 return viewContainerRef.createComponent(factory);
23 private getRootViewContainerRef(): ViewContainerRef {
24 return this.applicationRef.components[0].instance.viewContainerRef;