html - 如何通过 HTML 将字符串传递给 ng-template?
问题描述
假设我有一个像这样的 ng-template:
<ng-template #templateRef>
<button
(click)="testClick()"
Click me
</button>
<a
I'm a link
</a>
</ng-template>
然后我想在我的html模板中使用它
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="asdf"
>
</ng-container>
有什么方法可以让我将一个额外的变量传递给模板,以便根据我在 html 中使用模板的位置,我可以传递一个不同的字符串,我可以使用该字符串通过属性绑定设置自定义指令的值?IE 我真的希望最终结果是
<button
(click)="testClick()"
[customLocation]="top"
Click me
</button>
<a
[customLocation]="top"
I'm a link
>
</a>
和
<button
(click)="testClick()"
[customLocation]="bottom"
Click me
</button>
<a
[customLocation]="bottom"
I'm a link
>
</a>
所以当我使用模板时
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="asdf"
>
</ng-container>
我只想保留当前存在的所有内容,并将另一个变量传递到容器中,该变量将作为 customLocation 的值。这可以做到吗?任何帮助表示赞赏
解决方案
模板有一个上下文。在这里,我们创建了一个名为location
感谢语法的模板变量let-location
。该变量将绑定到上下文的 $implicit 属性。
<ng-template #templateRef let-location>
<button
[customLocation]="location"
</button>
</ng-template>
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="{$implicit: 'top'}"
>
</ng-container>
请注意,通过命名模板变量是可能的。它在https://angular.io/api/common/NgTemplateOutlet中有解释。
推荐阅读
- java - 查找 java.security.Security 中所有属性的当前状态
- java - 如何在 Crafter CMS 中设置站点?
- java - 将 ImageView 调整为所有可用空间
- c++ - C++ 中的非阻塞套接字 - 资源暂时不可用错误
- javascript - 相同的类型和相同的单词,但在询问它们是否相同时仍然返回 false
- c# - WPF 使用 Linq 将列表框绑定到 2 个表
- docusignapi - 将文本框字段和选项列表添加到通过 DocuSignAPI 发送的 pdf
- sql - 优化一个有大量记录被连接和组合的 sql 查询
- sql - 同一个外键如何在 SQL 中有多个引用?
- razor - Razor 如何区分 @ 符号的使用?