gpt4 book ai didi

Angular,在运行时编译和创建组件

转载 作者:行者123 更新时间:2023-12-03 18:38:02 24 4
gpt4 key购买 nike

我正在尝试以 Angular 制作文档生成工具,并且在如何允许用户动态创建内容方面遇到了挑战。

我要创建的组件可能具有任意模型和行为,因此我认为我不能使用共享组件。

我描述的组件在编译时不存在。

我看到一些 documentation for rendering dynamic components .但是它提到您必须在 entryComponents 中列出“动态”组件。在 ngModule .其中不会工作对于我的场景。

Is there another mechanism to get this effect?

最佳答案

您可以即时创建模块和组件,对其应用装饰器,然后全部编译。然后您将能够访问已编译的组件:

@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);
})
}

要使这种方法起作用,您需要将编译器带到运行时。有关动态组件的更多详细信息,请阅读文章:
  • Here is what you need to know about dynamic components in Angular
  • 关于Angular,在运行时编译和创建组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46576727/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com