【问题标题】:Angular - ng-template with parameter inside ngIf inside ngFor [duplicate]Angular - ng-template 在 ngFor 内的 ngIf 内带有参数 [重复]
【发布时间】:2026-01-12 13:40:01
【问题描述】:

我正在尝试构建这个模板:

<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

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

【问题讨论】:

    标签: angular angular-template ng-template


    【解决方案1】:

    你可以这样做:

    <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

    【讨论】:

    • 嗨 Vivek 我需要传递外部值(如输出)以访问另一个组件中的 [ngTemplateOutletContext] 请参阅此插件:plnkr.co/edit/lHFWI9KEHXPaJT4YKDkD?p=preview
    • 您的回答帮助我掌握了每个ng-template 都有自己的模板变量上下文的概念。最终帮助我建立了一个很棒的页面。谢谢!
    • 更新语法:&lt;ng-container *ngTemplateOutlet="simpleLink; context: {link: link}"&gt;&lt;/ng-container&gt;angular.io/api/common/NgTemplateOutlet
    • 嘿 Vivek,是否可以一次传递多个值?不过谢谢你的例子。
    • 是的,您可以将 json 传递给ngTemplateOutletContext,如上所示,每个键都被视为变量
    【解决方案2】:

    你可以这样使用

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

    【讨论】: