130

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.

Jacob Stamm
  • 1,660
  • 1
  • 29
  • 53
yanivps
  • 1,993
  • 3
  • 25
  • 33

2 Answers2

332

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

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • 1
    Hi Vivek i need to pass external values like output to access [ngTemplateOutletContext] in another component refer this plunker:https://plnkr.co/edit/lHFWI9KEHXPaJT4YKDkD?p=preview – Venkateswaran R Jan 30 '18 at 07:39
  • 3
    Your answer helped me grasp the concept that each `ng-template` has its own context of template variables. Ended up helping me build a great page. Thanks! – Jacob Stamm Jun 12 '18 at 15:35
  • 23
    Updated syntax: `` https://angular.io/api/common/NgTemplateOutlet – Anis Abboud Jun 06 '19 at 10:58
  • Hey Vivek, is it possible to pass multiple values at once? Thanks for the example though. – Hemang Jun 24 '20 at 19:40
  • 1
    Yes you can pass json to `ngTemplateOutletContext`,as shown above each key considered as variable – Vivek Doshi Jun 25 '20 at 02:47
-20

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>
Shrey Kejriwal
  • 726
  • 4
  • 13