且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Angular2中的组件渲染动态模板

更新时间:2023-08-25 20:54:10

问题已解决 Yurzui,

https:// plnkr。 co / edit / TAbupH4si62x10QZ7xuc?p =预览

通用HTML从不同的帖子中删除(在Angular 2.1.0中动态创建子组件,动态)可以用于使用自定义指令来渲染模板。

The generic HTML outlete from a different post (Angular 2.1.0 create child component on the fly, dynamically) can be used to render templates with custom directives in them.

不要忘记使用要呈现的所有自定义组件导入模块

Don't forget to import a module with all the custom components that you want to render!

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
const cmpClass = class DynamicComponent {};
const decoratedCmp = Component(metadata)(cmpClass);

<!-- Import the module with required components here -->
@NgModule({ imports: [CommonModule, RouterModule, SharedModule], declarations: [decoratedCmp] })
class DynamicHtmlModule { }

return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
   .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
    return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
  });
}