我想动态创建一个模板。这应该用于构建 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)
并了解我可以使用
ngIf
与 ComponentFactoryResolver
.如果我在 @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/