How to increment and update index value by 2 in ngFor while using a fixed structure

Issue

I have a fixed template structure to print only two items in a row as below and i need to iterate using ngFor directive:

 <div class="row" *ngFor="let item of cityCodes; let i = index">
    <div class="col-6" (click)="cityClick(item.key)">
      <div class="img img-1">

      </div>
      <div class="img-text">
        {{cityCodes[i].value}}
      </div>
    </div>
    <div class="col-6" (click)="cityClick(item.key)">
      <div class="img img-2">

      </div>
      <div class="img-text">
        {{cityCodes[i+1].value}}
      </div>
    </div>

  </div>

As you can see in the above code I am using cityCodes json as below:

  cityCodes=[{12:'patna'},{23:'jaipur'},{21:'Baliya'},{23:'Canugh'}]

Since I have a fixed structure like two columns in a row, i am using cityCodes[i] and cityCodes[i+1] to print the images side by side.

As I have already used [i+1]th item in the first row, ngFor is again starting with same item in the next row. How to update the index here.

Solution

IMHO, contrary to other answers here, I think following should be enough.

<div class="row" ; let i = index">
  <div class="col-6" *ngFor="let item of cityCodes" (click)="cityClick(item.key)">
    <div class="img img-1">
    </div>
    <div class="img-text">
      {{item.value}}
    </div>
  </div>
</div>

or to just wrap in an ng-template

<div class="row" ; let i = index">
  <ng-template ngFor let-item [ngForOf]="cityCodes">
    <div class="col-6" (click)="cityClick(item.key)">
      <div class="img img-1">
      </div>
      <div class="img-text">
        {{item.value}}
      </div>
    </div>
  </ng-template>
</div>

Answered By – Pushkar Adhikari

Answer Checked By – Marilyn (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.