【问题标题】:How do I string interpolate a ng-template ID into the ng-if Else condition?如何将 ng-template ID 字符串插入到 ng-if Else 条件中?
【发布时间】:2020-07-20 19:34:59
【问题描述】:
<div *ngFor="let user of users">
  <ng-template [attr.id]="'tileInactiveContent'+user">
    something...
  </ng-template>
  <div *ngIf="somecondition;else tileInactiveContent+{{ user }}">
    something...
  </div>
</div>

在上面的代码中,users是一个由4个字符串组成的字符串数组。

因此在最终代码中生成了 4 个 ng-templates,每个 ng-templates 都有一个唯一的 id。

问题

如何处理 ngIf 指令 else 部分中的 id? 'tileInactiveContent+{{ user }}' 的替代品是什么?

我知道 ng-template 可以用反转的 if 条件调用。但是还是……

【问题讨论】:

  • 为什么每次迭代都使用唯一ID?在角度中创建动态模板变量是不可能的
  • 为什么要将用户包含在 ng-template id 中?
  • @RafiHenig 你是在暗示 *ngFor 即使为所有模板提供了 same id 也会自行计算?
  • 所有迭代都使用相同的模板,?

标签: angular angular-ng-if string-interpolation ng-template


【解决方案1】:

从 Template 本身调用 Ts 函数,并在该函数中编写逻辑

getWhatever(index:any,user:User){
//do and return something
}
<div *ngFor="let user of users;let i=index;">
  <ng-template [attr.id]="'tileInactiveContent'+user">
    something...
  </ng-template>
  <div *ngIf="somecondition;else getWhatever(i,user)">
    something...
  </div>
</div>

【讨论】:

  • 函数绑定不是提高性能的好方法,它总是监听 html
  • 但这如何呈现所需的ng-template 而不是 div?
猜你喜欢
  • 1970-01-01
  • 2020-10-04
  • 2018-04-25
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 2023-03-27
相关资源
最近更新 更多