我正在将一个电子应用程序从 AngularJS 迁移到 Angular5,我在需要加载任意模块及其组件并将主要组件动态渲染到视图的部分遇到问题(它是一个插件系统)。
在我的应用程序中,插件是一个 Angular5 模块,其中包含在我的 Angular5 应用程序中呈现的组件。
我像这样动态加载组件:
@ViewChild("view", { read: ViewContainerRef })
view: ViewContainerRef;
constructor(
// ...
private compiler: Compiler,
private injector: Injector,
private moduleRef: NgModuleRef<any>
) {}
then,
const addonModule = addonObject.getModule();
this.compiler
.compileModuleAndAllComponentsAsync(addonModule)
.then(factories => {
const factory = factories.componentFactories.find(
componentFactory =>
addonObject.getViewComponent().name ==
componentFactory.componentType.name
);
if (factory) {
const cmpRef = factory.create(this.injector, [], null, this.moduleRef);
cmpRef.instance.config = {
from: "[email protected]",
apikey: "dsfkjd"
};
this.view.insert(cmpRef.hostView);
}
});
它工作得很好,但是当我在模板中添加材质组件时,它失败了factory.create()
出现此错误:
模板:
<div>
<button mat-button>test</button>
</div>
error:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[Renderer2]:
StaticInjectorError[Renderer2]:
NullInjectorError: No provider for Renderer2!
or
模板:
<div fxLayout="row" fxFlex>
test
</div>
error:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[MediaMonitor]:
StaticInjectorError[MediaMonitor]:
NullInjectorError: No provider for MediaMonitor!
材料模块似乎很好地导入到我的插件模块中,否则如果未加载它,我会有不同的行为:它忽略指令(例如<button mat-button></button>
只是一个<button></button>
无材料影响且无错误)和材料组件抛出错误(例如<mat-card>test<mat-card>
throws Error: Template parse errors: 'mat-card' is not a known element...
)
我尝试以多种不同的方式捆绑动态模块:tsc / ngc / ng-packagr / webpack。
当我在另一个使用 ng-cli 构建的应用程序的 NgModule 中正常(静态)导入该包时,该包正在工作。
有人知道如何动态渲染在模板中使用材质组件/指令的组件,例如 fxFlex / mat-button / mat-card 吗?
编辑:我在这里用 SystemJS 复制了该错误:https://github.com/thyb/repro-dynamic-loading
角度:5.0.2
角材料:5.0.0-rc1