首页 > 解决方案 > 如何从模板中获取与Angular中数组中的属性匹配的对象计数?

问题描述

假设我有以下数组“myarr”:

[
{'name':'Mary', 'chapter':'Chapter 1'},
{'name':'Joseph', 'chapter':'Chapter 1'},
{'name':'John', 'chapter':'Chapter 2'},
{'name':'Carl', 'chapter':'Chapter 3'},
{'name':'Jacob', 'chapter':'Chapter 3'}
]

我想计算这个数组中标题中有“第 1 章”的对象的数量。有没有办法在 Angular 的 HTML 模板中做到这一点?

现在我从模板中调用一个函数,如下所示:

{{countNumOf('Chapter 1')}}
{{countNumOf('Chapter 2')}}

使用处理 .ts 中的计数的函数...有没有更聪明的方法可以做到这一点,所以我不必在 .ts 中编写额外的函数?

标签: angular

解决方案


如果您可以使用 es6,那么这是最短的方法:

const count = source.filter(item => item.status === '0').length;

或者没有条件,比如只获取对象的数量:

const count = source.filter(item => item).length;

推荐阅读