Passing ngFor variable to an ngIf template

强颜欢笑 提交于 2019-11-27 06:42:56

问题


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


回答1:


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>

WORKING DEMO




回答2:


look here: Pass variable in Angular 2 template

<div *ngFor="foo in foos">
    <ng-container *ngTemplateOutlet="inner; context:{name:foo}"></ng-container>
</div>
<ng-template #inner let-name="name">
    {{ name }}
</ng-template>



回答3:


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 <ng-container> 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 <ng-template> 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.



来源:https://stackoverflow.com/questions/48204477/passing-ngfor-variable-to-an-ngif-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!