Angular - ng-template with parameter inside ngIf inside ngFor

AngularAngular TemplateNg Template

Angular Problem Overview


I am trying to build this template:

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

The problem is that the link variable is undefined inside the ng-template so I get an error of accessing 'some_property' of undefined.

I am struggeling to understand how I pass the link variable from the ngFor to the ng-template

It would be great to know if there are multiple solutions for this problem.

Angular Solutions


Solution 1 - Angular

You can do it like :

<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

Solution 2 - Angular

You can use it in this way

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyanivpsView Question on Stackoverflow
Solution 1 - AngularVivek DoshiView Answer on Stackoverflow
Solution 2 - AngularShrey KejriwalView Answer on Stackoverflow