Angular 2 : Pass string to ngTemplateOutlet

标签 angular templates angular2-template

我正在尝试为字符串数组的每个字段传递不同的模板。

TS

export class MyComponent {
  fields = ['name', 'person.age', 'created_at', ...]
}

HTML

<div *ngFor="let field of fields">
   <ng-container [ngTemplateOutlet]="field">
       
   </ng-container>
</div>

<ng-template #name>
   Name template
</ng-template>

<ng-template #created_at>
    Created at template
</ng-template>

<ng-template #person.age>
     person.age template
</ng-template>

我显然得到了一个错误,因为 ngTemplateOutlet 需要一个 TemplateRef 而不是一个字符串。但是我怎样才能动态地传递一个字符串来引用正确的模板呢?我得到的错误是:

Error : templateRef.createEmbeddedView is not a function

PS:这个问题可能有更好的解决方案。不要犹豫分享:)谢谢!

最佳答案

你可以这样写:

<div *ngFor="let field of fields">
   <ng-container *ngTemplateOutlet="{'name': name, 'created_at': created_at, 
     'person_age': person_age}[field]">

   </ng-container>
</div> 

<ng-template #name>
    Name template
</ng-template>

<ng-template #created_at>
    Created at template
</ng-template>

<ng-template #person_age>
     person.age template
</ng-template>

这不需要子组件。

关于 Angular 2 : Pass string to ngTemplateOutlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49976019/

相关文章:

angular - 如何等待两个异步 Ionic APP_INITIALIZER 完成?

模板类上的 C++ 运算符重载

loops - Angular 2 对象中的数据绑定(bind)

Angular 5 - 未定义谷歌(谷歌地图)

angular - 在 Angular 方法中返回类值

angular - 为网络和 ionic 应用程序设置不同的 'click_action'

angular - 在 component.ts 中找不到名称 '$'

python - 使用 django 表单模板

c++ - 如何将此宏转换为函数模板?

Angular 4 ObjectUnsubscribedError 删除和添加数据表时出错