How to Retrieve the Current Item in *ngFor Loop Using TypeScript in Angular 4

In my JSON file, I have an array containing 5 people. Each person in the array has a list of items associated with them. In my HTML code, I am using *ngFor to iterate over the people and display their names. Additionally, I want to display the total sum of the prices of all the items associated with each person. To calculate the total price of all the items for each person, I have a function in my TypeScript code. The total prices are then displayed in the console.

The issue I am encountering is that the current implementation in my TypeScript file involves looping through the list of people twice. This means that I am iterating over the people in my HTML using *ngFor and within this loop, calling the function getTotal(), which itself loops through the people again. Ideally, I would like to only loop through the people once.

JSON Object:

  "persons":[
    {
      "name": "Peter",
      "items": [
        {
          "name": "pen",
          "price": 1.50
        },
        {
          "name": "paper",
          "price": 2.00
        }
      ]
    },
    {
      "name": "Maria",
      "items": [
        {
          "name": "scissors",
          "price": 4.00
        },
        {
          "name": "stickers",
          "price": 3.00
        }
      ]
    }

    // three more persons
  ]

HTML Code:

<div *ngFor="let person of persons"> <!-- Looping through the persons here -->
  <p>{{person.name}}</p>
  <p>Total <span>{{getTotal()}}</span></p> <!-- Calling the function here, leading to another loop through persons -->
</div>

TypeScript Code:

getTotal() {
    for(let person of this.persons){ 
      let total = 0;
      for(let item of person.items){
          total += item.price;
      }
     console.log(total);
    }
}

Question: The current setup involves unnecessary duplication where I am looping through the people in both the HTML code using *ngFor and the TypeScript code within getTotal(). Is there a way to access the current element being iterated over in *ngFor without needing the initial loop in getTotal()? Can this be achieved or is it not possible?

Answer №1

Make the necessary changes

To address your inquiry, invoke a function from the template side. The following code snippet demonstrates it, although I recommend utilizing the second approach.

Template Side :

<p>Total <span>{{getTotal(person.items)}}</span></p> 

Component Side :

getTotal(items) {
    let total = 0 ;
    for(let item of items){
        total = total + item.price;
    }
    return total;
}

The preferred method is to handle all data processing on the component side rather than relying on the template side.

Why ?

In the previous scenario, the function would be invoked every time the view or data is modified.

Component Side :

constructor(){
    this.persons.map(person => {
        person.total = person.items.reduce((pv,cv) => {
            return cv.price + pv.price;
        });
        return person;
    });
}

Template Side :

<p>Total <span>{{person.total)}}</span></p> 

Answer №2

When utilizing the getTotal function, you have the ability to pass a person in and add the price of their items without the need for looping through them again.

<div *ngFor="let individual of persons">
  <p>{{individual.name}}</p>
  <p>Total <span>{{ getTotal(individual) }}</span></p> <!--in this case, the function is called without looping through persons again-->
</div>

Typescript

getTotal(person) { 
      let total = 0;
      for(let item of person.items){
          total = total + item.price;
      }  
      return total;
}

Answer №3

Pass the individual to the calculateTotal function like so:

calculateTotal(individual: any) {
   let totalCost: number = 0;
   for (item of individual.items) {
       totalCost += item.price;
   }
   return totalCost;
}

Therefore, in your HTML it should appear as follows:

<div *ngFor="let individual of individuals"> 
   <p>{{individual.name}}</p>
   <p>Total <span>{{calculateTotal(individual)}}</span></p> <!-- Note how I am passing the current individual in the *ngFor loop -->
</div>

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

Delivering emails with attachments using Angular 8

I've been attempting to send an email with an attachment using Angular 8. Here's the code I've tried: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51283e2423343c30383d11343c30383d7f323e3c"&g ...

Allow TypeScript function parameters to accept multiple elements from an enumeration

Enumerating my options. export enum Selection { CHOICE_ONE = 'one', CHOICE_TWO = 'two', CHOICE_THREE = 'three', CHOICE_FOUR = 'four', } I am looking to design a function that accepts an array, but re ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

JSON object management within Node-RED

Within the realm of Node-RED, I've stumbled upon an object message that looks something like this: { chatId: 111111111, messageId: 1111, type: "message", content: "VENT Auto", date: "2017-12-28T19:46:45.000Z",inbound: true } The challenge at hand is ...

How come validation errors are not appearing on the view?

As I continue to practice, I am working on this form. It successfully displays a console message, indicating the wiring is correct. However, an issue arises when I submit the form without entering any text in the input field, as it fails to show a validati ...

Displaying JSON data on a Django template

As I worked on developing a website, I encountered an issue. The JSON data I am sending from views.py to my template is not displaying any content. data = { "philip": {"age": 20, "salary": 10000}, "jerry": {"age": 27, "salary": 30000} } names ...

AngularTS regex that enforces the use of a decimal point in numbers

I am working on a requirement where the input should only accept decimal characters, negative or positive. I need to use regex to make the decimal point mandatory, however it is currently allowing negative whole numbers which is not the desired behavior. I ...

Can someone guide me on creating a JSON command to save user IDs in discord.py?

Although I haven't dabbled in coding before, I can provide a more thorough explanation of my objectives. The goal is to develop a new command called ""!hi". When a user inputs ""!hi"", their ID will be recorded in a JSON file. ...

What are some ways to enhance the design of Material Input Text boxes and make them more compact?

I have been developing an Angular application using Material UI v7, but I am finding that the input controls are not as compact as I would like them to be. I have attempted to customize them without success. Can someone provide guidance on how to achieve m ...

What is the process of launching an Angular component in a new browser tab?

I have a large amount of data that needs to be displayed on the screen in a simplified list format for users to choose an item and view its details. Consider a component called SimpleListComponent, which will store the data and present a condensed view: ...

Updating JSON Data Retrieved from C# AJAX Request

During my ajax call, I am fetching JSON data that is being returned from a query. The current JSON response looks like this: [{ "label": "", "value": "2302" }, { "label": "9 - Contract set-up in EPICOR", "value": "2280" }, { "label": " ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

When updating the data in a datatables.net table within Angular 7, the previous data from the initial table load is retained

I'm currently working on a project that involves live reporting from a REST API request using the datatables.net library in Angular 7. When I update data in the database, the table reflects these changes accurately. However, if I interact with the tab ...

Troubleshooting display glitches on Bootstrap modals in Internet Explorer 11 and Microsoft Edge

I have been encountering rendering artifacts consistently across various versions of IE11 and Edge, on different devices with varying graphics cards and drivers, as well as different update statuses of Windows 10. The screenshots indicate some of these ar ...

Scala string: Unescaping made easy

I have come across numerous discussions on escaping strings, but none on de-escaping them. When working with Scala Play, my controller takes in a JSON request. I retrieve a string from it using the following code: val text: play.api.libs.json.JsValue = r ...

Having trouble converting NSData object to NSDictionary

Could there be an issue with the JSON output that is causing strange encoding when trying to extract information from a JSON file found on a blog? JSON: [{ "title": "A visit to McSorley\u0027s Old Ale House", "subtitle": "", "summary": "&bs ...

Retrieve the URL of an embedded image using discord.py and verify its presence within a JSON file

Currently, I am attempting to verify the existence of a specific URL found in message.embeds[0].image.url within my JSON file. Below is the code snippet that I am using: import discord import json from datetime import datetime bot = commands.Bot(command_p ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Using Regular Expressions to Replace in a JSON Format

I am currently attempting to perform a Regex Replace on a JSON string that resembles the following: String input = "{\"`####`Answer_Options11\": \"monkey22\",\"`####`Answer_Options\": \"monkey\",\"Answer_Option ...

Retrieving every single .json file present in a specific folder

I'm working on developing an Android app that utilizes JSON data. Is there a method to establish a directory structure similar to this: http://......./jsons/*.json Or is there another way to append additional data into a JSON file (such as a.json) a ...