Angular 2 conditional ngFor

7ball picture 7ball · Dec 21, 2016 · Viewed 28.1k times · Source

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!

Answer

Matej Maloča picture Matej Maloča · Dec 21, 2016
  <li *ngFor="let a of (condition ? array1 : array2)">
    <p>{{a.firstname}}</p>
    <p>{{a.lastname}}</p>
  </li>