101

我正在尝试构建此模板:

<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>

问题是链接变量在 ng-template 中是未定义的,所以我在访问未定义的“some_property”时遇到错误。

我正在努力了解如何将链接变量从 ngFor 传递到 ng-template

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

4

2 回答 2

250

你可以这样做:

<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>

工作演示

于 2018-01-30T06:40:10.673 回答
-18

你可以这样使用

<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>
于 2018-01-30T06:49:38.137 回答