Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing ngFor variable to an ngIf template

Tags:

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

like image 506
match Avatar asked Jan 11 '18 10:01

match


People also ask

Can ngIf and ngFor be used together?

Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.

Can we use ngFor in ng-template?

It is used for grouping content that is not rendered, but that can be used in other parts of your code. Alternatively, (and preferably), you can also use the ng-template element by prefixing an asterisk (*), which is the shorthand syntax. For instance, *ngIf, *ngFor.

Can we apply ngIf to ng-template?

the element onto which the structural directive ngIf was applied has been moved into an ng-template. The expression of *ngIf has been split up and applied to two separate directives, using the [ngIf] and [ngIfElse] template input variable syntax.


1 Answers

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

like image 116
Vivek Doshi Avatar answered Oct 22 '22 12:10

Vivek Doshi