Chris
Chris

Reputation: 4728

Adding a where condition to an ngFor

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

Upvotes: 10

Views: 22398

Answers (2)

misbah
misbah

Reputation: 189

Completely from the view, you can filter out content as follows

<ng-container *ngFor="let p of (active | keys)">
    <div *ngIf="p.age > 18">
        {{ p.name }}
    </div>
</ng-container>

Upvotes: 2

Hugo Noro
Hugo Noro

Reputation: 3243

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

Upvotes: 28

Related Questions