Nesting *ngFor in Angular allows for a powerful way

I have a table that contains two nested iterations. The first three columns iterate through an array of objects (items), while the fourth column should iterate through an array of numbers (total=[30,70,100]).

<table class="table"> 
    <thead class="thead-dark"> 
        <tr>
            <th>Item</th>
            <th>Unit Price</th>
            <th>Quantity</th>
            <th>Amount</th>    
        </tr>        
    </thead>

    <tbody>        
        <tr *ngFor="let i of item">  

            <td>{{i.product}}</td>
            <td>{{i.price}}</td>
            <td>{{i.quantity}}</td>

            <ng-container *ngFor="let t of total">
                <td>{{t}}</td>
            </ng-container>

        </tr>
    </tbody>
</table>

The object array iterates correctly, but I am experiencing issues with the array of numbers (total=[30,70,100]). I have tried placing the

(<ng-container *ngFor="let t of total">)
at different levels, however, it is not populating in the intended way. Any advice on how to resolve this issue would be greatly appreciated.

Answer №1

If the indexes for the arrays are the same, you can effectively use the index to keep track of and repeat the elements.

<tr *ngFor="let i of item; let in=index">

  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>

  <ng-container *ngFor="let t of total[in]">
    <td>{{t}}</td>
  </ng-container>

</tr>

Update: If the original poster is multiplying quantity by price to calculate the total, there's no need for a separate array. You can simply perform the multiplication in the view:

<tr *ngFor="let i of item; let in=index">

  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>
  <td>{{i.price * i.quantity}}</td>


</tr>

Answer №2

To properly populate the data, it is important to ensure that the td tag iterates correctly with the total value. The total variable should be clearly defined either as a property within the item object or as a separate variable. Here are examples for different scenarios:

If the total is a property of each item and you want to display it in a single td:

<tr *ngFor="let i of item">  
  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>
  <td>{{i.total.join(,)}}</td>
</tr>

If the total is stored outside the item array and you want to display it in a single td:

<tr *ngFor="let i of item let index = index">  
  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>
  <td>{{total[index]}}</td>
</tr>

If you want to calculate the sum of the total values and display it in a single td (assuming total is a property of each item):

<tr *ngFor="let i of item">  
  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>
  <td>{{i.total.reduce((a, b) => a + b, 0)}}</td>
</tr>

If you want to calculate the sum of the total values stored outside the item array and display it in a single td:


<tr *ngFor="let i of item let index = index">  

  <td>{{i.product}}</td>
  <td>{{i.price}}</td>
  <td>{{i.quantity}}</td>
  <td>{{total[index].reduce((a, b) => a + b, 0)}}</td>
</tr>

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

d3: It appears that my routes are replicating themselves, and I am unable to ascertain the cause

I've been diving deep into D3, studying the works of Mike Bostock and other experts in the field. I'm also going through Scott Murray's book on Interactive Data Visualization specifically focusing on D3. At the moment, my project involves c ...

Trigger a jQuery event when a particular element has finished loading

Is there a way to globally detect when any element (such as textarea) is displayed on the page in order to perform a specific action? The element could also be added dynamically through an AJAX request. // This code snippet is just an illustration of the ...

Guide on establishing a connection to a server from a local database

Attempting to access an external database locally through my server, I ran the following code on the server side: console.log('MONGODB_URI_LOCAL::', config.MONGODB_URI_LOCAL) const mongooseLocal = require('mongoose'); const connectionO ...

How can I find the URL of a webpage that is not showing up in the search bar? Utilize Google Instant

I'm currently working on an extension and I've encountered a challenge... I'm trying to figure out how to extract the URLs from a Google instant search page. The browser's URL bar doesn't seem to update instantly, so I'm unsur ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

submit a new entry to add a record to the database

Hey there, I recently started learning PHP and JS and I'm trying to insert a row into a WordPress database table. I need to get the information needed for insertion from another table, but I'm facing an issue with the PHP file as it's not in ...

Retrieving the data from the <input> tag using TypeScript

I'm currently working on retrieving user input values from a form. While vanilla JavaScript allows me to easily target elements and get their values using the .value method, I've encountered some challenges with TypeScript. Despite TypeScript bei ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

Modify the buttons in the Angular Material Nav-bar according to the current page

I've utilized Angular Material to design my navbar in the app.component.html page. Initially, it features a LOGIN button which should be hidden once the user successfully logs in. Current method: I'm currently disabling the login button based on ...

Pausing or buffering an RxJS 6 observable when the page is inactive

Currently, I am dealing with a stream of letters that need to be arranged in the correct order to form a word. However, an issue arises when the user switches tabs, minimizes the browser, or switches applications - the behavior mimics using setTimeout(), r ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

Transmit information using JSON format in Angular 8 using FormData

i am struggling with sending data to the server in a specific format: { "name":"kianoush", "userName":"kia9372", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bcd7d5ddd8ce85...@example.com</a>" } H ...

Error encountered while trying to update a record using NodeJS, Express, and MySQL modules due to SQL syntax

When attempting to update a MySQL record in NodeJS, I encounter an "app crashed" error in Visual Studio Code's terminal. app2.js: const express = require('express'); const mysql = require('mysql'); // establish connection cons ...

Guide to retrieving an object by its unique Id from the server and populating a Form in Angular Template

As a newcomer to Angular, I apologize if this question seems a bit off. I am struggling with understanding how to incorporate editing functionality into this project. When I click on the Edit link, I expect the ID to be sent to the EditEmployeeComponent.t ...

Having trouble with the functionality of expanding rows in Kendo grid

I am facing an issue with my Kendo grid that is populated from a SQL database. The expand feature works perfectly and displays a different Kendo grid in the expanded row when the program is first launched. However, if I perform a new search and get differe ...

The canvas game's animation can only be activated one time

I am currently working on designing a straightforward canvas game: Here is the code snippet located on CodePen var canvas; var ctx; var x = 300; var y = 400; var r = 0; var mx = 0; var my = 0; var WIDTH = 600; var HEIGHT = 400; function circle(x,y,r) ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Attempting to save data to an external JSON file by utilizing fs and express libraries

I've encountered a challenge while attempting to serialize an object into JSON. Despite my best efforts, I keep encountering an error that has proven to be quite stubborn... Below is the code snippet that's causing the issue: APP.post('/api ...

What is the process for viewing the collections of all databases while logged in as an administrator?

My aim is to display all databases along with their collections, similar to logging in as an admin user into robo3T, for example. Using the two commands below poses no issue. However, when I use the listCollections command, I only get the collections from ...

Send data to local REST service with Jquery/Ajax for file upload

I am currently trying to implement a REST service that allows me to upload files to our database using the file explorer. So far, I have successfully managed to open the file explorer by clicking on my findDocumentOnboarding button within an input type="fi ...