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

2024-02-10

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

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

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

我看到一些渲染动态组件的文档 https://angular.io/guide/dynamic-component-loader。但是它提到您必须在中列出“动态”组件entryComponents in the ngModule. which 不管用对于我的场景。

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


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

@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 动态组件的知识 https://blog.angularindepth.com/here-is-what-you-need-to-know-about-dynamic-components-in-angular-ac1e96167f9e
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular,在运行时编译和创建组件 的相关文章

随机推荐