[英]How to pass a string into a ng-template via HTML?
Lets say I have an ng-template like so:假设我有一个这样的 ng-template:
<ng-template #templateRef>
<button
(click)="testClick()"
Click me
</button>
<a
I'm a link
</a>
</ng-template>
And then I want to use it in my html template like然后我想在我的 html 模板中使用它
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="asdf"
>
</ng-container>
Is there any way for me to pass one additional variable into the template so that depending on where I use the template in the html, I can pass a different string that I can use to set the value of a custom directive via property binding?有什么方法可以让我将一个额外的变量传递到模板中,以便根据我在 html 中使用模板的位置,我可以传递一个不同的字符串,我可以使用它来通过属性绑定设置自定义指令的值? IE I really want the end result to be
IE 我真的希望最终结果是
<button
(click)="testClick()"
[customLocation]="top"
Click me
</button>
<a
[customLocation]="top"
I'm a link
>
</a>
and和
<button
(click)="testClick()"
[customLocation]="bottom"
Click me
</button>
<a
[customLocation]="bottom"
I'm a link
>
</a>
So when I use the template like所以当我使用模板时
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="asdf"
>
</ng-container>
I just want to leave everything that's currently there as-is and pass one more variable into the container that will get put as the value for customLocation.我只想保留当前存在的所有内容,并将另一个变量传递到容器中,该变量将作为 customLocation 的值。 Can this be done?
这能做到吗? Any help is appreciated
任何帮助表示赞赏
templates have a context.模板有上下文。 Here we create a template variable named
location
thanks to the syntax let-location
.由于语法
let-location
我们在这里创建了一个名为location
的模板变量。 The variable will be binded to the $implicit property of the context.该变量将绑定到上下文的 $implicit 属性。
<ng-template #templateRef let-location>
<button
[customLocation]="location"
</button>
</ng-template>
<ng-container
[ngTemplateOutlet]="templateRef"
[ngTemplateOutletContext]="{$implicit: 'top'}"
>
</ng-container>
Note that it's possible to have template variables by naming them.请注意,可以通过命名来拥有模板变量。 It's explained in https://angular.io/api/common/NgTemplateOutlet .
它在https://angular.io/api/common/NgTemplateOutlet 中有解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.