...">

Angular 2 conditional ngFor

I am trying to clear my template code. I have the following:

<ul> <li *ngIf="condition" *ngFor="let a of array1"> <p>{{a.firstname}}</p> <p>{{a.lastname}}</p> </li> <li *ngIf="!condition" *ngFor="let b of array2"> <p>{{b.firstname}}</p> <p>{{b.lastname}}</p> </li> </ul> 

Is there a way to conditionally select array1 or array2 to iterate with *ngIf or something else, so that I don’t need to repeat so much template code? This is just an example; my actual <li> contains a lot more content, so I really don't want to repeat myself. Thanks!

+8
source share
5 answers
  <li *ngFor="let a of (condition ? array1 : array2)"> <p>{{a.firstname}}</p> <p>{{a.lastname}}</p> </li> 
+29
source

Use a template tag with [ngIf] outside the ngFor loop.

 <ul> <template [ngIf]="condition"> <li *ngFor="let a of array1"> <p>{{a.firstname}}</p> <p>{{a.lastname}}</p> </li> </template> <template [ngIf]="!condition"> <li *ngFor="let b of array2"> <p>{{b.firstname}}</p> <p>{{b.lastname}}</p> </li> </template> </ul> 

Also read about template syntax here: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template

0
source

You cannot have both *ngFor and *ngIf in one element. You can create an element inside <li> with *ngFor . How:

 <li *ngIf="condition"> <ul> <li *ngFor="let a of array1"> 

Or use a conditional expression inside *ngFor . Like this:

 <li *ngFor="let a of (condition?array1:array2)"> 

Or you can use a template like Peter Salomonsen .

0
source

You can use ng-container which is not recognized by the DOM, therefore it will be used only for conditions. See an example below:

  <tr *ngFor="let company of companies"> <ng-container *ngIf="company.tradingRegion == 1"> <td>{{ company.name }}</td> <td>{{ company.mseCode }}</td> </ng-container> </tr> 

The code above will be:

Show a list of all companies where tradingRegion == 1

''

0
source

We can hide the element using the bootstrap display property based on the condition.

 <li [ngClass]="{'d-none': condition}" *ngFor="let a of array1"> <p>{{a.firstname}}</p> <p>{{a.lastname}}</p> </li> 
0
source

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


All Articles