Angular - ng-template,其中ngIf内的参数位于ngFor内

yan*_*vps 31 angular-template ng-template angular

我正在尝试构建此模板:

<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>
Run Code Online (Sandbox Code Playgroud)

问题是在ng-template中未定义链接变量,因此我得到访问未定义的'some_property'的错误.

我很想知道如何将链接变量从ngFor传递到ng-template

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

Viv*_*shi 90

你可以这样做:

<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>
Run Code Online (Sandbox Code Playgroud)

工作演示

  • 更新语法:`&lt;ng-container *ngTemplateOutlet="simpleLink; context: {link: link}"&gt;&lt;/ng-container&gt;` https://angular.io/api/common/NgTemplateOutlet (9认同)
  • @Vivek谢谢你拯救我的生命! (3认同)
  • 您的回答帮助我掌握了每个`ng-template` 都有自己的模板变量上下文的概念。最终帮助我建立了一个很棒的页面。谢谢! (3认同)