This repository has been archived by the owner on Jun 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
runtime-content.component.ts
64 lines (50 loc) · 1.98 KB
/
runtime-content.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import {
Component,
ViewChild, ViewContainerRef, ComponentRef,
Compiler, ComponentFactory, NgModule, ModuleWithComponentFactories, ComponentFactoryResolver
} from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'runtime-content',
template: `
<div>
<h3>Template</h3>
<div>
<textarea rows="5" [(ngModel)]="template"></textarea>
</div>
<button (click)="compileTemplate()">Compile</button>
<h3>Output</h3>
<div #container></div>
</div>
`
})
export class RuntimeContentComponent {
template: string = '<div>\nHello, {{name}}\n</div>';
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
private componentRef: ComponentRef<{}>;
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private compiler: Compiler) {
}
compileTemplate() {
let metadata = {
selector: `runtime-component-sample`,
template: this.template
};
let factory = this.createComponentFactorySync(this.compiler, metadata, null);
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
}
private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> {
const cmpClass = componentClass || class RuntimeComponent { name: string = 'Denys' };
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
class RuntimeComponentModule { }
let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
}