Support of get_property in property assignment
[sdc.git] / catalog-ui / src / app / ng2 / services / dynamic-component.service.ts
1 import {
2     Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef
3 } from '@angular/core';
4
5
6
7 @Injectable()
8 export class DynamicComponentService {
9
10     constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
11
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();
17
18         const factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
19         return viewContainerRef.createComponent(factory);
20     }
21
22     
23     private getRootViewContainerRef(): ViewContainerRef {
24         return this.applicationRef.components[0].instance.viewContainerRef;
25     }
26 };