Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

angular - Passing ngFor variable to an ngIf template

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...