我试图在视图中通过引用带有传统Angular 2“#”字符的模板来动态选择模板。
在我的项目中,我处理错误并将它们显示给用户,我有一个对话框组件,它应该基于动态注入的内容HTML进行内容。
我读了一些文章,展示了如何在已知模板引用名称的情况下完成它的方法,在我的情况下,我不知道引用的名称,我在运行时获取名称。
我特别遵循了这个指南:https://www.bennadel.com/blog/3101-experimenting-with-dynamic-template-rendering-in-angular-2-rc-1.htm
所以目前我的对话框组件具有以下视图:
在我的dialog.ts文件中,我有以下代码:
<template #err_1 let-property1="p1" let-property2="p2">
property1: {{p1}}
property2: {{p2}}
</template>
<template #err_2 let-property1="p1" let-property2="p2">
<p *ngIf="p1">{{p1}}</p>
property2: {{p2}}
</template>
<!--The code for the template directive i took from the guide in the link above-->
<tem [render]="templateRef"
[context]="context">
</tem>
在我的dialog.ts文件中,我有以下代码:
@Component({
selector: 'error-dialog',
queries: {
templateRef: new ViewChild("err_1")
},
templateUrl: './dialog.html'
})
...
"TemplateRendererDirective"指令源代码来自于上面链接中的指南。 请注意,令我困惑的是: 即使指令最终获取到TemplateRef实例,但templateRef基本上获取到的是一个"ViewChild"对象,这怎么可能呢?
因此,只有当我知道要渲染哪个错误模板时,例如:"err_1",我才会预先在dialog.ts中引用它,但事实并非如此。我想动态地告诉它我想要渲染"err_1"、"err_2"等,并提供上下文(即填充该模板数据的对象-例如p1、p2也动态生成)
这是否可能?
templateRef
参数吗? - yurzuiViewChild
grabsTemplateRef
automatically if yourerr_1
hash relates to<template>
- yurzuingTemplateOutlet
指令,它与TemplateRendererDirective
执行相同的操作。https://www.bennadel.com/blog/3102-templates-appear-to-maintain-lexical-bindings-in-angular-2-rc-1.htm - yurzui