首页 > 解决方案 > 如何将上下文传递给 Angular 4 中 *ngIf 的 else 分支?

问题描述

下面的代码在嵌套的 ng-this 和 ng-that 标签方面已经有点暴行了,但是如果有一种方法可以跳过 ngSwitch 的 ngIf 并且只将上下文传递给 else 会更漂亮像分支一样

prop;context:{property: property}"

,如在模板中调用的 *ngTemplateOutlet 中所示。我希望我已经尽职尽责地寻找方法,但到目前为止,除了使用(另一个!)嵌套的 *ngTemplateOutlet 之外,我还没有其他选择。标记有点修剪到必要的东西。

<ng-template #prop let-property="property"> 
  <node-widget
    [property]="property.Nodes[1]"
  >
  </node-widget>
</ng-template>

<ng-container *ngFor="let property of lefties(Properties); let index = index">
  <ng-container [ngSwitch]="index">
    <node-widget *ngSwitchCase="0"
      [property]="property.Nodes[1]"
    >
    </node-widget>
    <ng-container *ngSwitchDefault>
      <ng-container *ngTemplateOutlet="prop;context:{property: property}">
      </ng-container>
    </ng-container>
  </ng-container>
</ng-container>

ng-template 在模板的其他地方被回收,所以我不能把它放在更靠近 ngSwitch 的地方(基本上在 *ngFor 里面)。我尝试用 *ngIf 替换整个 ngSwitch,但随后 prop 模板抱怨它没有定义 [property]。建议?我错过了什么吗?

标签: angularangular-ng-ifng-template

解决方案


推荐阅读