Passing ngFor variable to an ngIf template

后端 未结 4 433
清酒与你
清酒与你 2020-12-10 02:41

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,

4条回答
  •  抹茶落季
    2020-12-10 02:43

    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.

提交回复
热议问题