Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 conditional ngFor

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!

like image 375
7ball Avatar asked Dec 21 '16 18:12

7ball


People also ask

Can I add condition in * ngFor?

*ngFor condition is similar to any other for the condition we used in other languages. In the below example *ngFor is added to the Select option element as below. in this example, colorSet is an array containing values of colors.

Can we use two ngFor?

We use the NgFor directive to loop over an array of items and create multiple elements dynamically from a template element. The template element is the element the directive is attached to. We can nest muliple NgFor directives together.

Can we have ngIf and ngFor together?

Use ngFor and ngIf on same element It's very common scenario where we want to repeat a block of HTML using ngFor only when a particular condition is true. i.e., if ngIf is true.So in this case to use *ngIf and *ngFor on same element, place the *ngIf on a parent element that wraps the *ngFor element.

What is ngForOf?

ngForOf: NgIterable<T> : The value of the iterable expression. Useful when the expression is more complex then a property access, for example when using the async pipe ( userStreams | async ). index: number : The index of the current item in the iterable.


1 Answers

  <li *ngFor="let a of (condition ? array1 : array2)">
    <p>{{a.firstname}}</p>
    <p>{{a.lastname}}</p>
  </li>
like image 186
Matej Maloča Avatar answered Oct 20 '22 05:10

Matej Maloča