在我的角度应用程序中,我有以下内容:
export class MyComponent {
subcompPath = "path-to-subcomp#SubcompClassName";
@ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef;
/* Constructor where Compiler, ComponentFactoryResolver are injected */
loadSubcomponent() {
let [path, componentName] = this.subcompPath.split("#");
(<any>window).System.import(path)
.then((module: any) => module[componentName])
.then((type: any) => {
return this._compiler.compileComponentAsync(type)
})
.then((factory: any) => {
let componentRef = this.placeholderRef.createComponent(factory, 0);
});
}
}
我的子组件声明提供程序和东西,指令和管道。
现在,RC6再次打破了一切。组件不能声明指令和管道,但是它们必须在声明该组件的模块中。因此,我必须使用SystemJS加载组件本身而不是模块。好,那我应该用
return this._compiler.compileModuleAndAllComponentsAsync(type)
很好,但是如何获得该特定组件的出厂参考?该工厂就是我所需要的,placeholderRef希望在其createComponent方法中使用它,对吗?
我试图从github上挖掘angular2源代码,但是它相当庞大,我应该使用intellisense从VS Code或其他东西尝试,但是我很懒...而且我应该从文档中阅读这些东西,这在相当乏味的此特定参数的angular.io,是在没有路由器的情况下延迟加载组件和模块。
感谢您的任何帮助,我认为该解决方案易于应用,但是如果没有官方文档则很难找到。
基于yurzui的答案,我得出以下代码:
export class MyComponent {
subcompPath = "path-to-subcompMODULE#SubcompClassName";
@ViewChild("placeholder", { read: ViewComponentRef }) placeholderRef: ViewComponentRef;
/* Constructor where Compiler, ComponentFactoryResolver are injected */
loadSubcomponent() {
let [modulePath, componentName] = this.subcompPath.split("#");
(<any>window).System.import(modulePath)
.then((module: any) => module["default"]) // 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 === componentName); // Crucial: componentType.name, not componentType!!
let componentRef = this.placeholderRef.createComponent(factory, 0);
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句