0

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)"

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • https://stackoverflow.com/questions/17117712/how-to-know-if-all-javascript-object-values-are-true – Chellappan வ Dec 28 '18 at 13:30
  • Possible duplicate of [How to know if all javascript object values are true?](https://stackoverflow.com/questions/17117712/how-to-know-if-all-javascript-object-values-are-true) – Alex Feb 22 '19 at 12:41

4 Answers4

2

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));
Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
Saeb Panahifar
  • 479
  • 1
  • 5
  • 11
0
<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>
RamiReddy P
  • 1,628
  • 1
  • 18
  • 29
0

This should work:

*ngIf="data.Collection.reduce((a, b) => a || b.Flag, true)"
dquijada
  • 1,697
  • 3
  • 14
  • 19
0

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

Ajantha Bandara
  • 1,473
  • 15
  • 36