Angular - 在 ngFor 中的 ngIf 中带有参数的 ng-template

Angular - ng-template with parameter inside ngIf inside ngFor

我正在尝试构建此模板:

<ul>
    <li *ngFor='let link of links'>
        <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container>
    </li>
</ul>

<ng-template #simpleLink>
    ...
    {{ link.some_property }}
</ng-template>

<ng-template #complexLink>
    ...
    {{ link.some_property }}
</ng-template>

问题是 link 变量在 ng-template 中未定义,所以我在访问未定义的 'some_property' 时出错。

我很难理解如何将 link 变量从 ngFor 传递到 ng-template

很高兴知道这个问题是否有多种解决方案。

你可以这样做:

<ul>
    <li *ngFor='let link of links'>
        <ng-container 
             [ngTemplateOutlet]="link.type == 'complex' ?complexLink : simpleLink" 
             [ngTemplateOutletContext]="{link:link}">
        </ng-container>
    </li>
</ul>

<ng-template #simpleLink let-link='link'>
    Simple : {{ link.name }}
</ng-template>

<ng-template #complexLink let-link='link'>
    Complex : {{ link.name }}
</ng-template>

WORKING DEMO

可以这样使用

<ul>
  <li *ngFor='let link of links'>
      <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container>

      <ng-template #simpleLink>
          ... {{ link.some_property }}
      </ng-template>

      <ng-template #complexLink>
          ... {{ link.some_property }}
      </ng-template>
  </li>
</ul>