我试图制作一个有角度的文档生成工具,并且我正在尝试如何让用户动态创建内容。
我想创建的组件可能有任意模型和行为,所以我不认为我可以使用共享组件。
我描述的组件在编译时不存在。
我看到一些documentation for rendering dynamic components。但是它提到你必须列出"动态" entryComponents
中ngModule
中的组件。我的方案无效。
是否有其他机制可以达到此效果?
答案 0 :(得分:7)
您可以即时创建模块和组件,对其应用装饰器,然后将其全部编译。然后,您将能够访问已编译的组件:
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor(private _compiler: Compiler,
private _injector: Injector,
private _m: NgModuleRef<any>) {
}
ngAfterViewInit() {
const template = '<span>generated on the fly: {{name}}</span>';
const tmpCmp = Component({template: template})(class {
});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {
});
this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
.then((factories) => {
const f = factories.componentFactories[0];
const cmpRef = f.create(this._injector, [], null, this._m);
cmpRef.instance.name = 'dynamic';
this.vc.insert(cmpRef.hostView);
})
}
要使这种方法起作用,您需要将编译器带到运行时。有关动态组件的更多详细信息,请阅读以下文章: