【发布时间】:2018-07-03 07:56:02
【问题描述】:
假设我在组件模板中有这样的代码:
<div *ngIf="user?.name; else dash-template">{{user?.name}}</div>
这在另一个组件模板中:
<div *ngIf="data?.datum; else dash-template">{{data?.datum}}</div>
在这两种情况下,如果没有数据,我想将我的 div 替换为包含在 ng-template 中的模板(dash-template)。 现在我可以通过在两个文件中添加 dash-template 来归档它。
破折号模板代码:
<ng-template #dash-template>
<span>-</span>
</ng-template>
但一旦我决定更改 dash-template 的内容,我将需要更改每个文件中 dash-template 内容的每个实例。
我尝试在上层组件 (app.component.html) 中包含 dash-template 以及使用外部 html 文件并将其与 index.html 中的链接标记一起包含:
<head> ... <link rel="import" href="dash.template.html" > ... </head>
但在第一种情况下,我什么也没做:没有错误并且显示一个空字符串。 第二种情况(带链接标签),找不到html文件。
我的问题是:
有没有办法定义一个可重用的 ng-template,或者更常见的是一个可重用的 template reference variables ?
这是处理空数据的正确方法吗?
【问题讨论】:
标签: angular ng-template template-variables