【发布时间】:2018-10-03 04:48:25
【问题描述】:
我正在尝试为字符串数组的每个字段传递不同的模板。
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 而不是字符串。但是我怎样才能动态地传递一个字符串来引用正确的模板呢?我得到的错误是:
错误:templateRef.createEmbeddedView 不是函数
PS:这个问题可能有更好的解决方案。不要犹豫分享:)谢谢!
【问题讨论】:
-
你试过
*ngTemplateOutlet="field"吗? -
是的。同样的问题...它仍然被识别为字符串而不是 templateRef
-
我找到了一种解决方法:从 TS 中的函数传递引用:@ViewChild('name') name: ElementRef; getTemplateFromName(string) { return this.name }
名称模板 -
或者你可以使用子组件来替换 ng-container 元素
-
谁没有得到答案,请在此处阅读以获取更多说明blog.angular-university.io/…
标签: angular templates angular2-template