Elevate a counter value within a nested for loop in Angular framework

I need to update a count within a nested loop and display the value (e.g. 1,2,3,4) when the table loads. The challenge is that my objects have varying lengths, so with 100 rows in the table, the counter column should display numbers from 1 to 100.

<ng-container *ngFor= "let lot of all;">
        <tr *ngFor="let sensor of lot.income;" >
          <td>{{count++}}</td>  // incrementing counter
          <td>{{lot.project.name}}</td>
          <td>{{sensor.incomeNo}}</td>
        </tr>
</ng-container>

My JSON object structure looks like this:

[
  {
    "project": {
      "project": "project_one",
      "code": "0000001"
    },
    "income": [
      {
        "incomeNo": 1,
        "discount": 0
      },
      {
        "incomeNo": 2,
        "discount": 0
      }
    ]
  },
  {
    "project": {
      "project": "project_two",
      "code": "0000002"
    },
    "income": [
      {
        "incomeNo": 3,
        "discount": 2
      },
      {
        "incomeNo": 4,
        "discount": 8
      },
    {
        "incometNo": 5,
        "discount": 14
      },
    {
        "incomeNo": 6,
        "discount": 3
      }
    ]
  }
]

Answer №1

To enhance the functionality, consider introducing an additional local variable to manage the counter, such as: let i = index; Utilize the expression {{i + 1}} to commence your object from 1, ensuring a seamless operation.

<ng-container *ngFor= "let lot of all;">
        <tr *ngFor="let sensor of lot.income; let i = index" >
          <td>{{i + 1}}</td>  // display counter here
          <td>{{lotM.project.name}}</td>
          <td>{{sensor.incomeNo}}</td>
        </tr>
</ng-container>

Answer №2

To address the issue with the counter, I have implemented CSS counters. However, you will need to handle the design aspect accordingly. https://i.sstatic.net/oKer3.png

<table class="mainTable">
    <tr>
      <td width="20%">SR. No</td>
      <td width="20%">Income No</td>
      <td width="20%">Discount</td>
      <td width="20%">Name </td> 
      <td width="20%">Code</td> 
    </tr>
    <tr *ngFor="let sensor of ProductMain; let i = index">
      <td colspan="5">
        <table border="1" width="100%">
            <tr *ngFor="let lot of sensor.income; let i = index">
              <td width="20%" class="counter"><!-- Counter via CSS --></td>
              <td width="20%">{{lot.incomeNo}}</td>
              <td width="20%">{{lot.discount}}</td>
              <td width="20%">{{sensor.project.code}}</td>
              <td width="20%">{{sensor.project.project}}</td>
            </tr>
        </table>
      </td>
    </tr>
  </table>

Remember to add the following in your CSS file:

.mainTable{
    counter-reset: section;
}
.counter::before {
    counter-increment: section;
    content: counter(section) ") ";
}

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

Create an interactive and responsive user interface for Object using the Angular framework

After receiving a JSON Object from an API call with multiple string values, I need to create an Interface for this Object in the most efficient way possible. Rather than manually writing an Interface with 100 keys all of type string, is there a quicker a ...

What are the main challenges in resolving dependencies and implementing best practices when it comes to updating an outdated Angular NodeJS

After several months away, I am now faced with the challenge of updating and maintaining an out-of-date angular project. Seeking advice from experienced developers on how to tackle this situation. Previously, I used NPM update or upgrade commands to keep ...

Issue in Typescript: The method `clear` or `send` is not recognized in type `unknown` within Protractor framework

Having trouble using clear and sendKeys in Protractor with TypeScript. Could it be that I am missing certain dependencies, as even the click function is giving errors? I have attempted various solutions from Protractor clear() not working, but unfortunate ...

Exclude weekends from DateTime

Currently working on a task list and aiming to set the default date to 3 days from now, excluding weekends. Utilizing Vue and thinking a computed property might be the solution? DateTime.utc().plus({ days: 3 }).toFormat('yyyy-MM-dd HH:mm:ss'), ...

Limit the parameter of a TypeScript method decorator based on the method's type

Is it possible to generically restrict the argument of a method decorator based on the type of the method it is applied to? I attempted to obtain the method's type that the decorator is applied to using TypedPropertyDescriptor<Method>. However, ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

Using RxJS switchMap in combination with toArray allows for seamless transformation

I'm encountering an issue with rxjs. I have a function that is supposed to: Take a list of group IDs, such as: of(['1', '2']) Fetch the list of chats for each ID Return a merged list of chats However, when it reaches the toArray ...

Ways to avoid inaccurate information in Angular without relying on form functionalities

In my Angular application, I am looking for a way to easily validate number inputs without using forms. Specifically, I want to prevent users from entering values below 1 or greater than 99. I have successfully developed a component that displays dynamic d ...

Issues with Firebase Cloud Messaging functionality in Angular 10 when in production mode

Error: Issue: The default service worker registration has failed. ServiceWorker script at https://xxxxxx/firebase-messaging-sw.js for scope https://xxxxxxxx/firebase-cloud-messaging-push-scope encountered an error during installation. (messaging/failed-ser ...

Displaying a component within an ngFor loop

During my iteration over an array of objects, I encountered a situation where I needed to specify a component to load within the object. For instance, one of the items in the loop looks like: { label: 'Patient\'s Weight', subtitle ...

Angular 2 Return {responseBody: "assigned variable with [object Object]"}

In my Angular 2 application, I am encountering an issue where I am sending a variable from a service to a component. In the template, the variable appears as expected, however, when attempting to send this variable to a PHP script using POST, I receive [ ...

Guidelines for integrating a SOAP asmx service into an Angular+8 application using XML implementation

Here is the code snippet I'm struggling with: var xmlItemAll = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Library types for TypeScript declaration merging

Is there a way to "extend" interfaces through declaration merging that were originally declared in a TypeScript library file? Specifically, I am trying to extend the HTMLCanvasElement interface from the built-in TypeScript library lib.dom. While I underst ...

The issue with ngx-bootstrap-modal is that it fails to interpret HTML elements

In my Angular 5 project, I am implementing ngx-bootstrap-modal. Below is the code I am using to open the modal: this.dialogService.addDialog(PopUpComponent, { title: 'Custom locale', message: "Hello ? " }).subscribe((isConfirmed ...

After introducing 5 guard properties, the intersection of unions in Typescript breaks down

In TypeScript, I am attempting to create a class where properties are only accessible if another property has been checked on the class. This needs to be done in a generic manner to facilitate reuse across multiple classes. For instance, class Test { Fo ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

A guide on iterating through various JSON arrays and displaying them in AngularJS

I'm in the process of developing a new school management system and I need to showcase the list of departments along with the courses being offered by each department. The course information is saved in JSON format within the database. Here is my JSO ...

Having trouble with TypeScript error in React with Material-UI when trying to set up tabs?

I have developed my own custom accordion component hook, but I am encountering the following error export default const Tabs: OverridableComponent<TabsTypeMap<{}, ExtendButtonBase<ButtonBaseTypeMap<{}, "button">>>> Check ...