在运行时角化,编译和创建组件 [英] Angular, compile and create components at runtime

查看:56
本文介绍了在运行时角化,编译和创建组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个有角度的文档生成工具,并且在如何允许用户动态创建内容方面遇到了挑战.

I'm trying to make a document generation tool in angular and I'm hitting a challenge with how I would allow a user to dynamically create content.

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

My components I want to create could have arbitrary models and behavior so I don't think I could use a shared component.

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

The components I'm describing would not exist at compile time.

我看到了一些呈现动态组件的文档.但是,它提到您必须在ngModuleentryComponents中列出动态"组件.哪种不适用于我的情况.

I see some documentation for rendering dynamic components. However it mentions that you must list the "dynamic" component in entryComponents in the ngModule. which will not work for my scenario.

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

Is there another mechanism to get this effect?

推荐答案

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

You can create a module and a component on-the-fly, apply decorators to it and then compile it all. Then you will be able to access the compiled components:

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

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

For this approach to work you need to bring compiler to the runtime. For more details on dynamic components read the article:

这篇关于在运行时角化,编译和创建组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆