UNPKG

2.45 kBPlain TextView Raw
1import {
2 Component,
3 NgModule,
4 ComponentFactoryResolver,
5 Input,
6 ApplicationRef,
7 Injector,
8 ReflectiveInjector,
9 ComponentRef,
10 ViewContainerRef,
11 Compiler,
12} from '@angular/core';
13
14import { CommonModule } from '@angular/common';
15
16@Component({
17 selector: 'templation',
18 template: `<div></div>`
19})
20export class TemplationComponent {
21 @Input() imports: [];
22 @Input() template: string;
23 @Input() component: any;
24 @Input() componentDeps: [];
25 constructor(
26 private vr: ViewContainerRef,
27 private cfr: ComponentFactoryResolver,
28 private compiler: Compiler,
29 private appRef: ApplicationRef,
30 ) { }
31
32 ngOnInit() {
33 this.renderComponent();
34 }
35
36 renderComponent() {
37 const hasTemplate = !!this.template;
38 if (!this.component || !hasTemplate) return false;
39 const templatedComponent = this.returnTemplatedComponent();
40 const templationModule = this.returnTemplationModule({ templatedComponent });
41
42 this.compiler.compileModuleAndAllComponentsAsync(templationModule)
43 .then(factory => {
44 const compFactory = factory.componentFactories.find(x => x.componentType === templatedComponent);
45 const cmpRef = this.vr.createComponent(compFactory, 0);
46 });
47 }
48
49 // will be used to get dependecies from constructor of
50 // parent class
51 private getDeps(func) {
52 // First match everything inside the function argument parens.
53 const args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
54 // Split the arguments string into an array comma delimited.
55 return args.split(',').map(function(arg) {
56 // Ensure no inline comments are parsed and trim the whitespace.
57 return arg.replace(/\/\*.*\*\//, '').trim();
58 }).filter(function(arg) {
59 // Ensure no undefined values are added.
60 return arg;
61 });
62 }
63
64 returnTemplatedComponent() {
65 const deps = this.componentDeps;
66
67 const componentMeta = {
68 selector: 'templatedComponent',
69 template: this.template,
70 };
71
72 @Component(componentMeta)
73 class TemplatedComponent extends this.component {
74 constructor() {
75 super(...deps);
76 }
77 }
78
79 return TemplatedComponent;
80 }
81
82 returnTemplationModule({ templatedComponent }) {
83 const dynamicImports = this.imports;
84
85 @NgModule({
86 imports: dynamicImports,
87 entryComponents: [templatedComponent],
88 declarations: [templatedComponent]
89 })
90 class TemplationModule {}
91 return TemplationModule;
92 }
93
94}