如何通过HTML向ng-template传递字符串用于自定义指令属性绑定
实现方案
该需求完全可以实现,通过Angular自带的ngTemplateOutletContext上下文传递机制即可完成,不需要改动原有模板的业务逻辑,只需要做两处调整:
步骤1:调整ng-template定义,声明接收的参数
在模板定义头部声明要接收的变量,同时给需要绑定customLocation的元素加上属性绑定即可:
<ng-template #templateRef let-customLocation="customLocation"> <button (click)="testClick()" [customLocation]="customLocation" > Click me </button> <a [customLocation]="customLocation" > I'm a link </a> </ng-template>
其中let-customLocation="customLocation"的作用是从传入的上下文对象中取出key为customLocation的值,赋值给模板内部可访问的customLocation变量。如果要简化写法,也可以将上下文的默认$implicit属性设为目标值,对应模板声明只要写let-customLocation即可。
步骤2:调用模板时传入对应参数
调用时只需要给ngTemplateOutletContext传入对应值的对象即可,不需要修改其他模板内容:
场景1:customLocation取值为top
<ng-container [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{ customLocation: 'top' }" > </ng-container>
场景2:customLocation取值为bottom
<ng-container [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{ customLocation: 'bottom' }" > </ng-container>
如果后续需要传递多个参数,只需要在上下文对象中增加对应的key,同时在ng-template定义中新增对应的let-参数名="key名"声明即可,原有模板的点击事件、文本内容都不需要改动。
内容的提问来源于stack exchange,提问作者Matt Works
相关产品推荐
相关产品推荐

