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!
*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.
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.
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.
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.
<li *ngFor="let a of (condition ? array1 : array2)">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With