aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-ui/src/app/ng2/services/dynamic-component.service.ts
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-ui/src/app/ng2/services/dynamic-component.service.ts')
-rw-r--r--catalog-ui/src/app/ng2/services/dynamic-component.service.ts28
1 files changed, 28 insertions, 0 deletions
diff --git a/catalog-ui/src/app/ng2/services/dynamic-component.service.ts b/catalog-ui/src/app/ng2/services/dynamic-component.service.ts
new file mode 100644
index 0000000000..29dd1e9e09
--- /dev/null
+++ b/catalog-ui/src/app/ng2/services/dynamic-component.service.ts
@@ -0,0 +1,28 @@
+import {
+ Injectable, Type, ViewContainerRef, ApplicationRef, ComponentFactory, ComponentFactoryResolver, ComponentRef
+} from '@angular/core';
+
+
+
+@Injectable()
+export class DynamicComponentService {
+
+ constructor(private componentFactoryResolver: ComponentFactoryResolver, private applicationRef: ApplicationRef) { }
+
+ //Creates a component dynamically (aka during runtime). If a view container is not specified, it will append the new component to the app root.
+ //To subscribe to an event from invoking component: componentRef.instance.clicked.subscribe((m) => console.log(m.name));
+ public createDynamicComponent<T>(componentType: Type<T>, viewContainerRef?:ViewContainerRef): ComponentRef<T> {
+
+ viewContainerRef = viewContainerRef || this.getRootViewContainerRef();
+ viewContainerRef.clear();
+
+ let factory: ComponentFactory<T> = this.componentFactoryResolver.resolveComponentFactory(componentType); //Ref: https://angular.io/guide/dynamic-component-loader
+ let componentRef: ComponentRef<T> = viewContainerRef.createComponent(factory);
+ return componentRef;
+ }
+
+
+ private getRootViewContainerRef(): ViewContainerRef {
+ return this.applicationRef.components[0].instance.viewContainerRef;
+ }
+}; \ No newline at end of file