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

Managing Geolocation in Ionic2 presenting challenges

Attempting to utilize Geolocation in ionic2 for device location access. Referred to the official documentation on https://ionicframework.com/docs/native/geolocation/. Successfully installed the necessary packages: $ ionic plugin add cordova-plugin-geoloca ...

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...

Encountering an Error in Angular Material 8 due to the Import of the Unforeseen Directive 'MatCard'

I keep encountering the error message displayed above in the console. I am currently working with Angular Material version 8.2.3. In my app.module.ts file, I have the following import statements related to Angular Material: import { MatInputModule, MatBu ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Navigate to the previous page

What is the best way to navigate back to the last page in Angular 2? Can it be done like this? this._router.navigate(LASTPAGE); For instance, if page C includes a Go Back button, From Page A to Page C, clicking it will take you back to Page A. Fro ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

a user-friendly database solution for storing data in HTML 5 and Google Drive

Greetings, I am currently faced with the following dilemma: As I work on my angular 2 application, I find myself needing to save certain data. Personally, I have a preference for saving data in JSON format. Here is the scenario: Imagine a todo list where ...

Tips for transferring numerous photos from Angular 8 to ASP .NET Core

I have been struggling to find a solution for the issue I am facing. When sending multiple images from Angular using "from data", although the files are successfully sent in the network request, the parameters on the API method show count=0. Here is the s ...

Using json_encode incorporates the table name into the JSON format

I am encountering an issue with encoding JSON data from my MySQL table "contacts". The data in the row looks like this: { "contactList": [ { "userId":"1062", "name":"Test User 1" }, { "us ...

Serializing columns in SQL Server without using a key

In my database, there is a column labeled A which currently holds the value hello. I am looking to transfer this data into a new column called AJson and format it as ["hello"]. To accomplish this task, I need to use an SQL Server command. Alth ...

Typescript: Issue encountered with Record type causing Type Error

When utilizing handler functions within an object, the Record type is used in the following code snippet: interface User { id: string; avatar: string; email: string; name: string; role?: string; [key: string]: any; } interface Stat ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

Retrieve keys only in a concise list using JQ

I am working with a Pipfile.lock JSON file that requires parsing using the jq tool. The format of the file is as follows: { //... "default": { "value1": { // numerous nested properties with values ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

Converting JSON to CSV by iterating through nested objects and matching values with keys

There is a JSON data with even more deeply nested objects in the following format: { "Group": { "Group1": { "GroupA": { "value": "#fffff", "type& ...

Eliminate the use of backslashes in JSON responses when using the WordPress REST API

As I work on extending the Wordpress Rest API, I encounter backslashes even after adding json flags to eliminate them. Below is what I am attempting: stripslashes(json_encode(['success'=> true], JSON_FORCE_OBJECT | JSON_HEX_APOS)); The outpu ...

Factors that could potentially result in delays when executing MySQL insert queries

My current system consists of three main components: a CMS, a tablet application (APP), and a MySQL database. The CMS is equipped with an API that is responsible for handling data received from the APP and storing it in the database for display on the CMS. ...

Transforming JavaScript code with Liquid inline(s) in Shopify to make it less readable and harder to understand

Today, I discovered that reducing JavaScript in the js.liquid file can be quite challenging. I'm using gulp and typescript for my project: This is a function call from my main TypeScript file that includes inline liquid code: ajaxLoader("{{ &ap ...

reactjs error: Attempting to utilize the toLowerCase method on an undefined property during double mapping

My issue involves a JSON structure that requires mapping a function twice in a loop to access objects within an array. Once mapped, I need a textbox for searching the data list. However, I am encountering the following error: TypeError: Cannot read proper ...