我正在尝试为字符串数组的每个字段传递不同的模板。
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/