【问题标题】:Adding custom directive dynamically to ng-template in the component将自定义指令动态添加到组件中的 ng-template
【发布时间】:2018-07-03 09:27:04
【问题描述】:

我在我的一个项目中使用 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-component 中动态添加指令,因为我有其他约束不允许我直接在每个td 上使用它。如何解决这个问题?请帮忙。

【问题讨论】:

  • 你能给我们举个例子,说明阻止你在 td 中添加工具提示的约束吗?
  • 我无法想象会阻止静态添加指令的约束。
  • 你考虑过使用 Angular Material 吗?它的工具提示组件可以为您提供帮助。

标签: angular angular2-template


【解决方案1】:

假设你使用的tooltip指令不是结构指令,你可以使用*ngIf。

在 my-row-component.component.ts 上公开一个对象说 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>

您可以在 constraintObject 上实现一个方法 applyTooltipe,该方法将返回 true 或 false 并采用您需要确定约束的任何参数。

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    相关资源
    最近更新 更多