Jamith NImantha
Jamith NImantha

Reputation: 2227

increment a value counter in a nested for loop in Angular

I want to increment a counter value inside a nested for loop and print the value(like 1,2,3,4) when the table is loaded. But the problem is I have values with different length in my objects. think there are 100 rows in the table so the counter column must print 1-100.

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

My object is look like this in JSON.

[
  {
    "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
      }
    ]
  }
]

Upvotes: 0

Views: 3392

Answers (2)

Vinayak Rajguru
Vinayak Rajguru

Reputation: 74

I tried to work around with the counter issue, added CSS counters but you will have to manage the design. enter image description here

<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>

in css file add:

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

Upvotes: 1

Vinayak Rajguru
Vinayak Rajguru

Reputation: 74

You can add another local variable to hold the counter e.g: let i = index; like below. To start your object from 1 add {{i + 1}} this should work

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

Upvotes: 3

Related Questions