Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a where condition to an ngFor

Tags:

angular

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

like image 869
Chris Avatar asked Dec 16 '17 14:12

Chris


1 Answers

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 }}

like image 72
Hugo Noro Avatar answered Oct 19 '22 13:10

Hugo Noro