Я хочу загружать компоненты динамически, компоненты в app.module будут загружены, но компоненты в ленивом модуле не будут.
Я пытаюсь использовать этот код.
import {
Injectable,
ComponentFactoryResolver,
ComponentFactory,
} from '@angular/core';
import {
NgModule,
Component,
Directive,
Input,
ReflectiveInjector,
ViewContainerRef,
Compiler,
ModuleWithComponentFactories
} from '@angular/core';
import { AboutUsComponent } from "../pages/about-us/about-us.component";
@Injectable()
export class ExampleService {
rootViewContainer: ViewContainerRef;
subcompPath = "app/lab/lab.module#LabModule";
constructor(private factoryResolver: ComponentFactoryResolver, private
vcRef: ViewContainerRef, private compiler: Compiler) { }
setRootViewContainerRef(view: ViewContainerRef): void {
this.rootViewContainer = view;
}
reset(): void {
this.rootViewContainer.clear();
}
insertHappyComponent(): void {
this.insertComponent(AboutUsComponent);
}
insertSadComponent(): void {
this.insertComponent(AboutUsComponent);
}
insertComponent(componentType: any): void {
const factory = this.factoryResolver.resolveComponentFactory(componentType);
this.rootViewContainer.createComponent(factory);
}
loadSubcomponent(compname: string) {
let [modulePath, componentName] = this.subcompPath.split("#");
(<any>window).System.import(modulePath)
.then((module: any) => module["LabModule"]) // Or pass the module class name too
.then((type: any) => {
return this.compiler.compileModuleAndAllComponentsAsync(type)
})
.then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
const factory = moduleWithFactories.componentFactories.find(x => x.componentType.name === compname); // Crucial: componentType.name, not componentType!!
let componentRef = this.rootViewContainer.createComponent(factory as ComponentFactory<any>, 0);
});
}
}
Он загружает компоненты из основного модуля, но не из LabModule, который является ленивым модулем.
Я нашел некоторый код, который я должен загрузить и скомпилировать ленивые модули и загрузить их компоненты, но я не знаю, как именно это сделать.