我正在为我的一个项目使用 angular 4,我遇到使用 ng-template 渲染我的表格行的情况如下。
//my-row-component.component.ts
<tr>
<ng-template [ngTemplateOutlet]="rowTemplate" [ngTemplateOutletContext]="{ row: data}">
</ng-template>
</tr>
其中 rowTemplate 是类的输入属性。并且此组件将用作
<table>
<my-row-component [rowTemplate] = "rowTemplate2"></my-row-component>
</table>
<ng-template #rowTemplate2 let-row="row">
<td [innerHTML]="row.id"></td>
<td [innerHTML]="row.displayName"></td>
<td [innerHTML]="row.location"></td>
</ng-template>
现在的问题是我必须添加一个工具提示,该提示将在动态悬停每个td时显示。我不能直接在模板td
上使用工具提示,我必须在 my--row 组件中动态添加指令,因为我还有其他约束不允许我直接在每个td
上使用它。怎么办呢?请帮忙。
假设您使用的工具提示指令不是结构指令,则可以使用 *ngIf
.
在 my-row-component.component.ts 上公开一个对象 say constraintObject,该对象将用于查看约束并决定是否应用指令。将此对象传递给行模板上下文:
<tr>
<ng-template [ngTemplateOutlet]="rowTemplate" [ngTemplateOutletContext]="{row: data, constraints: constraintObject}">
</ng-template>
</tr>
使用*ngIf
行内模板(这里我只在位置列上应用它(:
<ng-template #rowTemplate2 let-row="row" let-constraints="constraintObject">
<td [innerHTML]="row.id"></td>
<td [innerHTML]="row.displayName"></td>
<td *ngIf="constraints.applyTooltipe(row.location)" [tooltipDirective]
[innerHTML]="row.location"></td>
<td *ngIf="!constraints.applyTooltipe(row.location)"
[innerHTML]="row.location"></td>
</ng-template>
您可以在约束对象上实现一个方法applyTooltipe,该方法将返回true或false,并采用确定约束所需的任何参数。