Tips on how to increase and update the index value by 2 within an ngFor loop while maintaining a fixed format

I have a specific template layout that displays only two items in each row as shown below. I want to use the ngFor directive to iterate through them:

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

The above code snippet demonstrates my usage of the cityCodes JSON array:

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

Because I'm following a fixed structure of displaying two columns per row, I am accessing the items using cityCodes[i] and cityCodes[i+1] to display images side by side.

After utilizing the [i+1]th item in the first row, the ngFor directive restarts with the same item in the subsequent row. How can I update the index in this scenario?

Answer №1

In my humble opinion, I believe that the following code should suffice.

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

Alternatively, you can simply enclose it within 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>

Answer №2

Do you wish to showcase content side by side? This can be achieved using a simple CSS property called columns

To do this, you will need to separate the elements into two arrays: one for items at even indexes in the main array, and another for items at odd indexes.

Afterwards, loop through each of these arrays separately and utilize the CSS property to display them side by side.

.ulClass {
  columns: 2
}
<ul class='ulClass'>

  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>
  <li>1</li>



</ul>

Answer №3

To conditionally execute code, simply wrap it in a div and make use of the isOdd method that you can create in your TypeScript file.

<div class="row" *ngFor="let item of cityCodes; let i = index">
   <div *ngIf="isOdd(i)">
    <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>
  </div>

Answer №4

It may seem a bit like a hack, but you have the option to avoid it if the condition i % 2 === 1 is met.

<div class="row" *ngFor="let item of cityCodes; let i = index" *ngIf="i % 2 === 0">

Answer №5

<section class="city-section" *ngFor="let item of cityCodes; index as i; first as isFirst; even as isEven">
  <ng-container *ngIf="isEven || isFirst">
    <div class="city-column col-6" (click)="cityClick(item.key)">
      <div class="city-info border border-primary"></div>
      <div class="index-info border border-primary">{{i}}</div>
    </div>
    <div class="city-column col-6" (click)="cityClick(item.key)">
      <div class="city-info border border-primary"></div>
      <div class="index-info border border-primary">{{i+1}}</div>
    </div>
  </ng-container>
</section>

Check out the code on stackblitz here

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

Adding individual flag icons for each country in your Datatables can be a significant enhancement to

Below is the code snippet in JavaScript with flags: <script type="text/javascript"> $(document).ready(function() { var dataTable = $("#example").DataTable( { processing: true, bSort: false, ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

Ways to showcase the object on the console

How can I display the object function in the console? When I try, nothing is displayed. Can you please help me figure out what went wrong? I know I must have made a mistake somewhere, as this is my first question on Stack Overflow. import React, ...

Is there a way to retrieve an HTML file from a different directory using Express?

I am currently utilizing an HTML file in the same folder. How can I access an HTML file saved in a different folder using express? Thank you. const express=require('express') const path=require('path') const app=express() app.get(& ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

Tips for using jQuery to create a delete functionality with a select element

I'm relatively new to utilizing jquery. I decided to tackle this project for enjoyment: http://jsbin.com/pevateli/2/ My goal is to allow users to input items, add them to a list, and then have the option to select and delete them by clicking on the t ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

What is the method for stopping a slide in this script?

Welcome everyone! Check out this piece of code I have: <script type="text/javascript" > $(function(){ var time = 10000;//milliseconds var index = 0; var container = $("#containerr"); var child ...

Header vanishes while using a JavaScript function to search through an HTML table

I'm facing an issue with a search function in a php script. The search function, written in javascript, is designed to sift through the table below and extract matching content as the user inputs text into the search field. It looks specifically withi ...

Organize an array of JSON objects based on a specific key and eliminate any duplicated entries

I am grappling with the challenge of grouping an array of JSON objects by the id_commande attribute and eliminating any duplicates. I am finding it quite perplexing to figure out a solution to this issue without relying on a library like lodash. Ideally, I ...

Is it possible to implement H-Screen in Tailwind without causing the page size to expand? My website has a fixed navbar at the top, and I

My setup includes PanelMaster, along with Panel 1 and Panel 2 components. PanelMaster: flex Panel1: flex-col Panel2: flex-col I have a Navbar component at the top of the page with 'h-1/5' applied to it. However, I'm facing an issue where ...

What is the best way to access a variable from a different function in JavaScript?

In my current project, I have implemented a function that fetches a JSON string from an external URL. The JSON data is being retrieved successfully and is functioning as expected. However, I am facing an issue with the variable 'procode'. I need ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

What is the process by which Angular2+ ngFor directive cycles through the ref iterable?

My curiosity led me to dive into the inner workings of the Angular *ngFor directive. I was particularly interested in understanding how Angular interprets the iterable object passed to the directive - whether it re-evaluates it at each loop iteration simil ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

Using localStorage in the client side of nextJS is a breeze

Encountering an error while attempting to retrieve local storage data. Even with the use client directive in place at the beginning, the issue persists. 'use client'; const baseURL = 'https://localhost:7264'; const accessToken = localSt ...

The function Waterline.create() is not available

Currently in the process of building a basic REST API using Sails.js and Waterline-ORM, I've encountered an issue regarding Post.create is not a function when trying to create an object within the ORM on a Post request. Here is my model: module.expor ...

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

Is it feasible to return data when utilizing the ModalController in Ionic 5, specifically when executing a swipeToClose or backdropDismiss action?

With the latest update to Ionic 5's ModalController, a new feature allows users to swipe down on a modal to close it in addition to using the backdropDismiss parameter. Here is an example of how to enable this functionality: const modal = await this. ...

Ways to update the values of several different indexes at once:

worldArray = [["." for i in range(5)] for i in range(5)] This code generates a map that is utilized in my game. It will display as follows: [['.', '.', '.', '.', '.'], ['.', '.', &apo ...