What is the best way to loop through count fields, calculate the total, and display the result using string interpolation in Angular 2

Utilizing Angular 2's *ngFor and string interpolation, I am able to iterate over sub-fields and display them on the screen alongside their respective "count" values. Here is an example of the data structure in the database:

[
  {
    "_id": {
      "status": "gold",
      "sub": "Category A"
    },
    "count": 19
  },
  {
    "_id": {
      "status": "gold",
      "sub": "Category B"
    },
    "count": 27
  },
  {
    "_id": {
      "status": "gold",
      "sub": "Category C"
    },
    "count": 24
  },
  {
    "_id": {
      "status": "",
      "sub": "Category D"
    },
    "count": 11
  }
]

Displayed in the view using the following code snippet:

<ul class="action-list">
    <li *ngFor="let record of records" class="action">{{record._id.sub}}<span class="action-counts">{{record.count}}</span></li>
</ul>

The counts service is invoked in the component as follows:

ngOnInit() {
    this.streamGoldCountsService.getCount()
        .subscribe(resRecordsData => this.records = resRecordsData,
        responseRecordsError => this.errorMsg = responseRecordsError);
}

Everything is functioning correctly so far.

I am now faced with a challenge - how can I calculate the total count of all sub-fields and display it on the screen? Since we don't have this total stored in the database, I will need to perform some calculations within the component. Any suggestions on the best approach for achieving this?

Answer №1

To calculate the total count of records, you can simply loop through the data using the following code snippet:

  getTotalCount(data) {
    let total = 0;

    data.forEach((record) => {
      total += parseInt(record.count, 10);
    });

    return total;
  }

For a working example, check out this Plunker demo: https://embed.plnkr.co/LPhJgZvnEWzx5RQUoabV/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue encountered: Angular material table is not providing support for truncating cell text with ellipsis

Greetings! I am currently utilizing Angular Material table in my grid. While mat-table automatically adjusts the cell height to accommodate long text, I prefer to maintain a consistent height and display ellipsis instead. Does anyone have any suggestions ...

Ways to reach out to an item on a page that is loaded dynamically

On my webpage firstpagemidle.php, I have a div with the following code: DIV id="news" data-pageNum_rsnews="1" data-totalRows_rsnews="9" class="new"> To load this page on another page, I use the following code: $( ...

Are there any additional performance costs associated with transmitting JSON objects instead of stringified JSON data through node.js APIs?

When developing node.js APIs, we have the option to send plain JSON objects as parameters (body params). However, I wonder if there is some extra overhead for formatting. What if I stringify the JSON before sending it to the API and then parse it back to i ...

Total Tally of All UL Elements - Including Those Within Others

I'm currently working on using jQuery to count all <li> tags within a list, including the nested ones inside a separate <ul>. However, I have been unsuccessful so far and I haven't found a solution to this issue. In the example below, ...

Issue with dynamic imports and lazy-loading module loadChildren in Jhipster on Angular 8, not functioning as expected

When utilizing dynamic import, it is necessary to modify the tsconfig.json file in order to specify the target module as esnext. ./src/main/webapp/app/app-routing.module.ts 14:40 Module parse failed: Unexpected token (14:40) File was processed with these ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

What is the process for creating a jQuery object in TypeScript for the `window` and `document` objects?

Is there a way to generate a jQuery object in TypeScript for the window and document? https://i.stack.imgur.com/fuItr.png ...

Stop observing changes from the store in NgRx effects for easy management of

I am implementing a straightforward effect: @Effect() simpleEffect = this.actions.pipe( ofType<ActionA>('Action A'), withLatestFrom(this.store.select(selectSomething)), map(([action, something]) => console.log('CALLED TWICE&ap ...

What is the best method for extracting information from different websites? I typically utilize the $.post function for this task

Currently conducting a test on a javascript code located on localhost. The script is dependent on receiving data in JSON format from a remote server. Strangely, when I manually access the JSON url, the data loads without issue. However, when using JavaScri ...

JavaScript prohibiting input prior to execution

Having trouble with executing this javascript before the user input, can anyone assist me in resolving this issue. I just want to create a simple html page with a textbox and a button. When the button is clicked, it should open a new window with a modifie ...

An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

Adding elements to a webpage dynamically using the jQuery append method

<ul> <li><a href="">not here</a></li> <li><a href="">append text only if child ul is present</a> <ul> <li><a href="">not here</a></li> <li><a href=""> ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

The results of the jQuery selector appear differently in the browser console compared to PhantomJS

What could be causing the discrepancy in results when using the same jQuery selector? Visit this website for reference: See below code involving node.js and phantomjs-node(bridge): phantom.create(function(ph){ ph.createPage(function(page){ p ...

Is there a way to make a selected option stay selected in vue.js 2?

Here is the structure of my Vue component : <template> <select class="form-control" v-model="selected" :required @change="changeLocation"> <option :selected>Choose Province</option> <option v-for="option in o ...

Utilizing AngularJS ng-click and href attributes in anchor tags

Having both an ng-click and a href on an anchor causes the ng-click to not work. My goal is to have both functions work simultaneously - navigate to a route and run a function. In my situation, I want to close a drawer that is open with a panel of links wh ...

Using traditional JavaScript, bring in a class from Node.js

I have a mix of files utilizing the Node.js framework and others that I'd like to incorporate without it. When attempting to import a class from my Node files, where module.exports was used, into my JavaScript files, I encounter an error stating "the ...

Using an arrow function within an alert box that activates when clicking the 'onsubmit' button in a form

I have a code that currently outputs the function as is, but I want it to return the value of the 'p8' id using an arrow function. <form onsubmit="alert(()=>{document.getElementById('p8').value})"> <label>PA ...

Troubles encountered when attempting to use Axios to call a third-party API in a React JS application

Challenge Description: I set out to create a dropdown menu of post-offices based on the user-entered pincode. To achieve this, I utilized an API and Axios for the backend request. While I successfully populate the dropdown with the necessary data, the is ...

Is it the event loop that checks for event completion, or does the kernel or operating system send notifications

Node.js initializes the event loop when it starts, processing the input script which may include async API calls, timers, or process.nextTick(), and then begins processing the event loop. There are seven phases, each with its own event queue based on FIFO ...