-
Notifications
You must be signed in to change notification settings - Fork 1
/
compose.component.ts
66 lines (54 loc) · 1.7 KB
/
compose.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
65
66
import { Component, OnInit, Input, ViewContainerRef, ComponentRef, ViewChild, ModuleWithComponentFactories, Compiler, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'app-compose',
templateUrl: './compose.component.html',
styleUrls: ['./compose.component.css']
})
export class ComposeComponent implements OnInit {
@Input() modulePath: string;
@Input() className: string;
@Input() dynState: string;
@ViewChild("placeholder", { read: ViewContainerRef }) placeholderRef: ViewContainerRef;
comp: any;
private isViewInitialized: boolean = false;
constructor(
private compiler: Compiler,
private componentFactorResolver: ComponentFactoryResolver) { }
loadSubcomponent() {
if (!this.isViewInitialized) {
return;
}
if (this.comp) {
this.comp.destroy();
}
(<any>window).require([this.modulePath], (module) => {
let type = module["default"];
this.compiler.compileModuleAndAllComponentsAsync(type)
.then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
const factory = moduleWithFactories
.componentFactories
.find(x => x.componentType.name === this.className);
this.comp = this.placeholderRef.createComponent(factory, 0);
if (this.dynState) {
if (typeof this.comp.instance.setDynState == 'function') {
this.comp.instance.setDynState(this.dynState);
}
}
});
});
}
ngOnInit() {
}
ngOnChanges() {
this.loadSubcomponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.loadSubcomponent();
}
ngOnDestroy() {
if (this.comp) {
this.comp.destroy();
}
}
}