Passing ngFor variable to ngIf template

How to pass the current variable in the ngFor loop to ngIf if it uses templates with then / else syntax?

It looks like they go through normally when inline is used, but not accessible from the 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>

Templates do not seem to have access at numberall, but it works if used in a string.

A full example of working and non-working versions at the following link: plunkr

+7
source share
3 answers

All you need is to use Read more[ngTemplateOutletContext]

Here is the way you can achieve this:

<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

+8
source

see here: passing a variable in an Angular 2 template

<div *ngFor="foo in foos">
    <ng-container *ngTemplateOutlet="inner; context:{name:foo}"></ng-container>
</div>
<ng-template #inner let-name="name">
    {{ name }}
</ng-template>
+2

, . Angular javascript, , {{ number }} ng-template number *ngFor, , , <ng-container>.

number AppComponent, number = 42, , {{number}} <ng-template> 42.

So, either you have to define your templates inside the area *ngForwhere the variable numberhas the required value, or somehow pass this value to both even_tpl, and odd_tpl. As @Vivek pointed out, you can do this with ngTemplateOutletand ngTemplateOutletContext.

0
source

Source: https://habr.com/ru/post/1692033/


All Articles