angular - 如何使用/创建动态模板来使用 Angular 2.0 编译动态组件?

标签 angular typescript compilation angular2-compiler

我想动态创建一个模板。这应该用于构建 ComponentType在运行时并将其放置(甚至替换)托管组件内部的某个位置。

在 RC4 之前,我一直在使用 ComponentResolver ,但使用 RC5 我收到以下消息:

ComponentResolver is deprecated for dynamic compilation.
Use ComponentFactoryResolver together with @NgModule/@Component.entryComponents or ANALYZE_FOR_ENTRY_COMPONENTS provider instead.
For runtime compile only, you can also use Compiler.compileComponentSync/Async.

我找到了这份文件 (Angular 2 Synchronous Dynamic Component Creation)

并了解我可以使用
  • 种动态ngIfComponentFactoryResolver .如果我在 @Component({entryComponents: [comp1, comp2], ...}) 中传递已知组件- 我可以使用 .resolveComponentFactory(componentToRender);
  • 真正的运行时编译,带有 Compiler ...

  • 但问题是如何使用 Compiler ?上面的注释说我应该调用:Compiler.compileComponentSync/Async - 又怎样?

    例如。我想为一种设置创建(基于一些配置条件)这种模板

    <form>
       <string-editor
         [propertyName]="'code'"
         [entity]="entity"
       ></string-editor>
       <string-editor
         [propertyName]="'description'"
         [entity]="entity"
       ></string-editor>
       ...
    

    在另一种情况下,这个( string-editor 被替换为 text-editor )

    <form>
       <text-editor
         [propertyName]="'code'"
         [entity]="entity"
       ></text-editor>
       ...
    

    依此类推(不同的编号/日期/引用 editors 按属性类型,为某些用户跳过了一些属性...)。即这是一个示例,实际配置可能会生成更多不同和复杂的模板。

    模板正在更改,所以我无法使用 ComponentFactoryResolver并通过现有的...我需要 Compiler 的解决方案.

    最佳答案

    在 2021 年,Angular 仍然无法使用动态 HTML(动态加载 html 模板)创建组件,只是为了节省您的时间。
    即使有很多投票赞成的解决方案和接受的解决方案,但至少目前它们都不适用于生产/AOT 中的最新版本。
    基本上是因为 Angular 不允许你定义组件:
    模板:{变量}
    正如 Angular 团队所说,他们不会支持这种方法!!
    请引用 https://github.com/angular/angular/issues/15275

    关于angular - 如何使用/创建动态模板来使用 Angular 2.0 编译动态组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38888008/

    相关文章:

    javascript - ionic2/angular2 中的后续 promise

    angular - 从引用中获取 Angular 组件的名称

    javascript - 使用链接标签预加载图像 - 删除警告 (html/Javascript)

    javascript - React + TypeScript : Passing React Component as Props, 使用 props 渲染 [错误:TS2339]

    c++ - 函数名称之前的预期初始化程序

    django - 401 未经授权 ("detail":"Authentication credentials were not provided.")

    angular - 按下按钮时 Ionic2 关闭 fab 菜单

    angularjs - 如何使用 Typescript 实现过滤器?

    c++ - 让 GLEW 在 Code::Blocks 中进行编译

    c# - 将文件嵌入已编译的 .exe