Angular 2 conditional ngFor
Asked Answered
K

5

19

I'm trying to clean up 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 pick array1 or array2 to iterate through using *ngIf or something so that I don't have 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!

Kinky answered 21/12, 2016 at 18:19 Comment(0)
U
62
  <li *ngFor="let a of (condition ? array1 : array2)">
    <p>{{a.firstname}}</p>
    <p>{{a.lastname}}</p>
  </li>
Unintentional answered 21/12, 2016 at 18:25 Comment(1)
Thanks! Exactly what I need.Kinky
H
7

You can make use of the ng-container which is not recognised by DOM, hence will only be used for a condition. See 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: `

Display a list of all companies where the tradingRegion == 1

`

Hilliary answered 21/5, 2018 at 15:39 Comment(2)
this will create unnecessary tr rowsFormally
We can swap the the ng-container and the tr tag. No more unnecessary rows.Asphyxiant
A
1

Use a template tag with an [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

Arceliaarceneaux answered 21/12, 2016 at 18:31 Comment(0)
D
0

You cannot have both an *ngFor and an *ngIf in the same element. You could create an element inside the <li> with the *ngFor. Like:

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

Or use the conditional inside the *ngFor. Like this:

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

Or you could use a template like Peter Salomonsen instructed.

Deuteragonist answered 21/12, 2016 at 18:40 Comment(0)
C
0

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

<li [ngClass]="{'d-none': condition}" *ngFor="let a of array1">
 <p>{{a.firstname}}</p>
 <p>{{a.lastname}}</p>
</li>
Chamber answered 24/5, 2018 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.