Angular 2 conditional ngFor

34,657

Solution 1

  <li *ngFor="let a of (condition ? array1 : array2)">
    <p>{{a.firstname}}</p>
    <p>{{a.lastname}}</p>
  </li>

Solution 2

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

`

Share:
34,657

Related videos on Youtube

7ball
Author by

7ball

Updated on May 27, 2020

Comments

  • 7ball
    7ball almost 4 years

    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!

  • 7ball
    7ball over 7 years
    Thanks! Exactly what I need.
  • qaisjp
    qaisjp about 4 years
    this will create unnecessary tr rows
  • habla2019
    habla2019 almost 2 years
    We can swap the the ng-container and the tr tag. No more unnecessary rows.