【问题标题】:Is there any way to refer the current template in *ngIf有没有办法在 *ngIf 中引用当前模板
【发布时间】:2021-03-17 08:57:06
【问题描述】:

所以正常的ngIf是这样的

<div *ngIf="condition; else secondTemplate"></div>

我的condition 很复杂,因为我想在满足条件时创建secondTemplate,否则创建当前模板。

condition 是这样的,我不能使用 !condition 并使其工作,我必须使用没有否定的条件。

另外,我无法切换模板。

那么有什么可以参考当前模板的吗?像thiscurrent,引用当前模板。像这样的

<div *ngIf="condition? then secondTemplate else this"></div>

【问题讨论】:

  • condition 究竟是如何制定的?作为一般规则,避免在模板中进行任何复杂的计算并将它们移动到控制器中。
  • @MichaelD 解释起来有点复杂。有没有办法引用当前模板?
  • 您的问题不清楚。 “引用当前模板”到底是什么意思?你总是可以做&lt;div *ngIf="condition; then thenBlock else elseBlock"&gt;&lt;/div&gt;。见这里:angular.io/api/common/NgIf

标签: angular angular-ng-if


【解决方案1】:

您可以使用ng-template

<span *ngIf="condition == true;else elseBlock">IF Template</span>
<ng-template #elseBlock>
  <span>Else Template</span>
</ng-template>

【讨论】:

    【解决方案2】:

    您可以像这样使用then-else 组合:

    <ng-container *ngIf="condition; then template1; else template2>
       <ng-template #template1>
         Your code for condition-1
       </ng-template>
       <ng-template #template2>
         Your code for condition-2
       </ng-template>
    </ng-container>
    

    【讨论】:

      猜你喜欢
      • 2017-04-26
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 2011-11-13
      • 1970-01-01
      • 2011-03-27
      • 2017-02-08
      相关资源
      最近更新 更多