How do I pass the current variable in an ngFor loop to ngIf, if it is using templates with then/else syntax?
It appears that they pass through fine when used inline, but aren't accessible from a template, for example:
<ul *ngFor="let number of numbers">
<ng-container *ngIf="number % 2 == 0; then even_tpl; else odd_tpl"><>/ng-container>
</ul>
<ng-template #odd_tpl>
<li>Odd: {{number}}</li>
</ng-template>
<ng-template #even_tpl>
<li>Even: {{number}}</li>
</ng-template>
The templates don't seem to have access to number
at all, but it works if used inline.
A full example of the working and not-working versions in the following link: plunkr
All you need is to use [ngTemplateOutletContext]
Read More
Here is the way how you can achieve that :
<div>
<h3>All Templates</h3>
<ul *ngFor="let number of numbers">
<ng-container [ngTemplateOutlet]='number % 2 == 0 ? even_tpl : odd_tpl' [ngTemplateOutletContext]="{number:number}"></ng-container>
</ul>
</div>
<ng-template #odd_tpl let-number='number'>
<li>Odd: {{number}}</li>
</ng-template>
<ng-template #even_tpl let-number='number'>
<li>Even: {{number}}</li>
</ng-template>