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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With