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
It's because the way template scope works. Templates in Angular have dynamic scope instead of regular javascript lexical scope, that means, the
{{ number }}
expression inside theng-template
is not pointing to the samenumber
variable in your*ngFor
, although one should think it would since you're kinda evaluating the template expression where<ng-container>
is.If you actually define a
number
property in yourAppComponent
, let's saynumber = 42
, you can see that all the{{number}}
expressions inside<ng-template>
evaluates to42
.So either you should define your templates inside the scope of the
*ngFor
, where thenumber
variable has the desired value, or somehow pass this value to botheven_tpl
andodd_tpl
. As @Vivek has pointed out, you can do this withngTemplateOutlet
andngTemplateOutletContext
.All you need is to use
[ngTemplateOutletContext]
Read MoreHere is the way how you can achieve that :
WORKING DEMO
look here: Pass variable in Angular 2 template