【问题标题】:Angular, compile and create components at runtimeAngular,在运行时编译和创建组件
【发布时间】:2018-03-16 13:08:36
【问题描述】:

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

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

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

我看到了一些documentation for rendering dynamic components。但是它提到您必须在ngModule 中列出entryComponents 中的“动态”组件。哪个对我的场景不起作用

还有其他机制可以达到这种效果吗?

【问题讨论】:

    标签: angular dynamic compile-time


    【解决方案1】:

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

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

    要使这种方法起作用,您需要将编译器引入运行时。有关动态组件的更多详细信息,请阅读文章:

    【讨论】:

    • 嗨。谢谢(你的)信息。您是否碰巧知道 angular 8/ivy 的这种变化?我相信您现在可以将 AOT 用于您的核心,并将 JIT 用于动态生成的代码
    • @user5328504,目前还不清楚。我们需要稍等片刻才能获得此信息,直到 Ivy 发布
    • 在 Angular8 中,当在代码中调用 compileModuleAndAllComponentsAsync 时,我确实收到错误消息“错误:未加载运行时编译器”。有什么线索吗?
    • @MaxKoretskyi,现在Ivy来了,可以给@user5328504的问题指路吗?
    • 我会喜欢@MaxKoretskyi
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2015-11-17
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多