我使用'ngComponentOutlet'和'Compiler.compileModuleSync'来编译带有某些组件的动态模块。我希望我可以逐步编译动态模块。或者,我可以删除组件或将组件添加到动态模块中,而不是每次都编译整个动态模块。花了很多时间。
import {Compiler, Component, Input, NgModule, NgModuleFactory, OnChanges, OnInit, SimpleChanges} from "@angular/core";
import {HTTP_INTERCEPTORS, HttpClient} from "@angular/common/http";
import {RouterModule, Routes} from '@angular/router';
import {TranslateModule, TranslateService} from '@ngx-translate/core';
@Component({
selector: 'uid-dynamic',
template: `
<ng-container *ngComponentOutlet="dynamicComponent; ngModuleFactory: dynamicModule;">
</ng-container>
`
})
export class DynamicComponent implements OnInit, OnChanges {
dynamicComponent: any;
dynamicModule: NgModuleFactory<any>;
@Input()
dynamicStr: string;
@Input()
component: string;
constructor(private compiler: Compiler) {
}
ngOnChanges(changes: SimpleChanges) {
if (changes['dynamicStr'] && !changes['dynamicStr'].isFirstChange()) {
this._createClasses(this.dynamicStr);
}
}
ngOnInit() {
this._createClasses(this.dynamicStr);
}
private _createClasses(dynamicStr) {
let tempComponents = [];
[...there are componen code...].forEach((item) => {
tempComponents.push(this.createNewComponent(item.code))
});
let dynamicComponent = this.createNewComponent(dynamicStr);
let dynamicModule = null;
if (dynamicComponent) {
dynamicModule = this.compiler.compileModuleSync(this.createComponentModule(tempComponents));
}
if (dynamicComponent && dynamicModule) {
this.dynamicComponent = dynamicComponent;
this.dynamicModule = dynamicModule;
}
}
protected createComponentModule(componentTypes: any[]) {
@NgModule({
imports: [
AgentModule, PerfectScrollbarModule,TranslateModule.forRoot(), LayoutModules,
],
declarations: componentTypes,
providers: [],
entryComponents: componentTypes
})
class RuntimeComponentModule {
constructor() { }
}
// a module for just this Type
return RuntimeComponentModule;
}
protected createNewComponent(dynamicStr: string) {
try {
return eval(dynamicStr);
} catch (e) {
console.error('eval dynamic component source code failed: ' + e);
return null;
}
}
}
使用Compiler.compileModuleSync似乎无法增量编译动态模块。我不知道还有其他方法可以使用。