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,
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 the ng-template
is not pointing to the same number
variable in your *ngFor
, although one should think it would since you're kinda evaluating the template expression where
is.
If you actually define a number
property in your AppComponent
, let's say number = 42
, you can see that all the {{number}}
expressions inside
evaluates to 42
.
So either you should define your templates inside the scope of the *ngFor
, where the number
variable has the desired value, or somehow pass this value to both even_tpl
and odd_tpl
. As @Vivek has pointed out, you can do this with ngTemplateOutlet
and ngTemplateOutletContext
.