Angular 7 - 如果任何项具有属性 true,则对象的集合



如果集合中有任何项目具有 true 属性,如何对集合运行*ngIf

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

我该怎么做*ngIf="data.Collection.ANY(Flag == true)"

你可以

方便地在这里使用js some(),如下所示-

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

这是一个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));

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

如果你也想处理未定义

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

这应该有效:

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

在组件中编写一个函数

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

现在调用该函数

*ngIf="hasFlag()"

希望你不会得到绑定错误

最新更新