2017-10-05 116 views
1

我正在尝试在角度中生成一个文档生成工具,并且我正在如何允许用户动态创建内容。角度,在运行时编译和创建组件

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

我描述的组件在编译时不会存在。我看到documentation for rendering dynamic components。但是它提到您必须在ngModule中列出entryComponents中的“动态”组件。 对我的场景不起作用

是否有另一种机制来获得这种效果?

回答

2

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

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

对于此方法的工作,您需要将编译器带入运行时。有关动态组件的更多详细信息,请阅读文章: