0

Assuming I have the following array "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'}
]

I want to count the number of objects in this array that have "Chapter 1" in the title. Is there any way to do this within the HTML template in angular?

Right now I call a function from the template like this:

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

with the function handling the count in the .ts... is there a smarter way to do this so I don't have to write an extra function in the .ts?

Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 2
    The smarter way **is** to write an extra function in the .ts. That way, the template stays simple and readable, and focuses on presentation rather than logic. The componentTypeScript code is where the logic is supposed to be. Puttin it there also makes it much easier to test and optimize, and avoids code duplication in the template. – JB Nizet Nov 18 '19 at 23:45
  • I agree with @JBNizet, i would write a pipe for this – enno.void Nov 19 '19 at 00:09
  • Implementing the pipe in the link will help you I think. https://stackoverflow.com/a/44770768/10377603 – nevzatopcu Nov 19 '19 at 00:17
  • Never write method in template as it will be called and executed at every change detection and will slow down the performance. Use pipe implementation which can be pure or impure pipe depending upon scenario. – Himanshu Sharma Nov 19 '19 at 04:41

1 Answers1

0

If using es6 is ok for you, here's the shortest way:

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

Or without condition like just get the count of objects:

const count = source.filter(item => item).length;
radeveloper
  • 926
  • 2
  • 12
  • 20