将ngFor变量传递给ngIf模板 [英] Passing ngFor variable to an ngIf template

查看:146
本文介绍了将ngFor变量传递给ngIf模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果正在使用具有then/else语法的模板,如何将ngFor循环中的当前变量传递给ngIf?

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>

模板似乎根本无法访问number,但是如果以内联方式使用,则可以使用.

The templates don't seem to have access to number at all, but it works if used inline.

以下链接中的工作版本和不工作版本的完整示例: plunkr

A full example of the working and not-working versions in the following link: plunkr

推荐答案

您所需要做的就是使用[ngTemplateOutletContext] 了解详情

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

这篇关于将ngFor变量传递给ngIf模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆