I am looping through an array but would like to only show a subset of the elements.
I am using this code to loop through every element of active
<div *ngFor="let p of (active | keys)">
{{ p.name }}
</div>
Here is some pseudo code to demonstrate what I am looking for:
<div *ngFor="let p of (active | keys) where p.age > 18">
{{ p.name }}
</div>
Is there any way to specify conditions so only those with p.age > 18
will be shown?
I know I could use an *ngIf
within the loop but I am curious to see whether I can apply my condition within the *ngFor
Usually as a good practice you should reduce as much as you can having logic on the view. Having this I would filter the array on the component and then iterate it on the view.
If you want you can keep the original array and then create a getter for the filtered array
get filterByAge() {
return active.filter( x => x.age > 18);
}
And then in your loop just do
<div *ngFor="let p of filterByAge">
{{ p.name }}
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