user2818430
user2818430

Reputation: 6029

Angular 7 - collection of objects if any item has a property true

How can I run an *ngIf on a collection if there is any item in collection that has a property true?

var data ={
  Collection: [
     {Flag : true },
     {Flag : true },
     {Flag : true },
     {Flag : false }
  ]
}

how can I do *ngIf="data.Collection.ANY(Flag == true)"

Upvotes: 0

Views: 638

Answers (4)

Ajantha Bandara
Ajantha Bandara

Reputation: 1531

Write a function as bellow in your component

public hasFlag(): boolean {
  return this.data.collection && this.data.collection.some(item => item. Flag);
}

Now call to that function

*ngIf="hasFlag()"

Hope you won't get the binding error

Upvotes: 0

Saeb Panahifar
Saeb Panahifar

Reputation: 489

You can conveniently use js some() here as follows -

<div *ngIf="data.Collection.some(x=>x.Flag)"></div>

Here's a working example for some() -

var data ={
  Collection: [
     {Flag : true },
     {Flag : true },
     {Flag : true },
     {Flag : false }
  ]
}

// you may use it this way too - x => x.Flag == true
console.log(data.Collection.some(x => x.Flag));

Upvotes: 2

dquijada
dquijada

Reputation: 1699

This should work:

*ngIf="data.Collection.reduce((a, b) => a || b.Flag, true)"

Upvotes: 0

sriam980980
sriam980980

Reputation: 1988

<div *ngIf="data.Collection.filter(x=>x.Flag).length"></div>

if you want to handle undefined also

 <div *ngIf="data.Collection&&data.Collection.filter(x=>x.Flag).length"></div>

Upvotes: 0

Related Questions