将 ngFor 变量传递给 ngIf 模板 [英] Passing ngFor variable to an ngIf template
问题描述
如何将 ngFor 循环中的当前变量传递给 ngIf,如果它使用带有 then/else 语法的模板?
看起来它们在使用内联时可以正常通过,但不能从模板访问,例如:
<ng-container *ngIf="number % 2 == 0; then even_tpl; elseodd_tpl"><>/ng-container>
<ng-template #odd_tpl><li>奇数:{{number}}</li></ng-模板><ng-template #even_tpl><li>偶数:{{number}}</li></ng-模板>
这些模板似乎根本无法访问 number
,但如果使用内联则它可以工作.
以下链接中工作和不工作版本的完整示例:plunkr>
您只需要使用 [ngTemplateOutletContext]
阅读更多
以下是实现这一目标的方法:
<h3>所有模板</h3><ul *ngFor="let number of numbers"><ng-container [ngTemplateOutlet]='number % 2 == 0 ?even_tpl :odd_tpl' [ngTemplateOutletContext]="{number:number}"></ng-container><ng-template #odd_tpl let-number='number'><li>奇数:{{number}}</li></ng-模板><ng-template #even_tpl let-number='number'><li>偶数:{{number}}</li></ng-模板>
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>
这篇关于将 ngFor 变量传递给 ngIf 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!