In my Angular RC5 app I used the following code to dynamically load components:
public LoadComponentAsync(componentPath: string, componentName: string, locationAnchor: ViewContainerRef) {
(<any>window).System.import(componentPath)
.then(fileContents => {
return fileContents[componentName];
})
.then(component => {
this.resolver.resolveComponent(component).then(factory => {
let comp = locationAnchor.createComponent(factory, 0, locationAnchor.injector).instance;
//...
});
});
}
A component I was loading looked like this:
import { Component } from "@angular/core";
@Component({
selector: "my-test",
template: `Test`,
})
export class Main {
constructor() {
alert("Test");
}
}
Since ComponentResolver is depricated, I am looking for a new solution. I could not find one. The most promising solution I found so far:
loadSubcomponent(modulePath: string, componentName: string) {
(<any>window).System.import(modulePath)
.then((module: any) => module[componentName])
.then((type: any) => {
return this.compiler.compileModuleAndAllComponentsAsync(type)
})
.then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
const factory = moduleWithFactories.componentFactories.find(x => x.componentType.name === componentName);
let componentRef = this.extensionAnchor.createComponent(factory, 0);
});
}
Source: Angular2 RC6 - Dynamically load component from module
Unfortunately, it does not work as I expected. When I call this.loadSubcomponent("/main", "Main"); I get the following error message:
core.umd.js:2834 EXCEPTION: Uncaught (in promise): Error: No NgModule metadata found for Main
Any suggestions?