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

Exploring the handling of the nth element within a jQuery each loop

In the process of looping through elements using an each loop, function test(){ $('#first li').each(function(n){$(this).//jQuery effects for nth li of first \\ need to process nth li of id="second" simultaneously }); Is there a wa ...

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

Ajax handling all tasks except for adding HTML elements

Having an issue with my basic "Load More on Scroll" AJAX function. The console is showing that the HTML is being sent back from the request, but for some reason, nothing is being rendered on the page. I must be missing something really simple here. $(wi ...

Different ways to analyze elements from 2 arrays to hone in on specific values

I'm really struggling to solve this issue. I have two arrays - one for cars and the other for active filters. The cars array consists of HTML li tags with attributes like car type, number of seats, price, etc. On the other hand, the active_filters arr ...

Utilize string variables within TypeScript's enumeration feature

Can string variables be used in enums in TypeScript? Strings can be used in enum like so: enum AllDirections { TOP = 'top', BOTTOM = 'bottom', LEFT = 'left', RIGHT = 'right', } However, trying to use variab ...

I keep encountering the ExpressionChangedAfterItHasBeenCheckedError error in Angular, even though I'm calling it before the view is checked. What could

This is a piece of code that I have been working on home-component.ts export class HomeComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked { loading = false; constructor() { } ngOn ...

javascript send variable as a style parameter

screen_w = window.innerWidth; screen_h = window.innerHeight; I am trying to retrieve the dimensions of the window and store them in variables. Is there a way to then use these variables in my CSS styles? For example: img { width: screen_w; height: s ...

Connection lost from JS client in Twilio's Programmable Chat

My React application utilizes the Twilio Programmable Chat library for chat functionality. The setup code typically appears as follows, enclosed within a try/catch block: this.accessManager = new AccessManager(twilioToken.token); const chatClientOptio ...

Explore the latest update in the AngularJS single page application that introduces a new feature specifically designed for the initial login

Our AngularJS single page application has a new feature that we are ready to launch for customer use. We want to inform the logged in user about this new feature so they can start using it. We are looking for a small animated information symbol with a too ...

Content sliding to the left due to modal prompt

I've searched through various questions and answers but haven't been able to resolve this issue. There's a modal on my page that is causing the content to shift slightly to the left. I've created a sample fiddle, although it doesn&apo ...

ESLint is notifying that the prop validation for ".map" is missing, with the error message "eslint react/prop-types" occurring in a Typescript React environment

Hey everyone, excited to be posting for the first time! Currently, I'm working on a small project using Typescript and React. I've run into an issue with ESLint where it doesn't recognize that a prop variable of type string[] should have a ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Exploring the similarities between using jQuery AJAX post and Angular

In my current project, I have a legacy application that relies on jQuery and unfortunately cannot incorporate Angular at this time. For one specific task, I need to make an AJAX POST request to consume a web service using jQuery. Interestingly, the same ...

Exploring the potential of Oracle Openscript in combination with Javascript using AngularJS,

I have encountered an issue while using Openscript on a form page with a clickable "save" button implemented as a div. Manually clicking the button triggers a javascript event that saves any changes made on the page. However, when I run the script, the but ...

CSS styles are combined and included at the beginning of the index.html file

During the creation of a production version of my Angular 9.0.4 application, I noticed that the CSS is bundled and placed at the top of the dist/index.html file as shown below: <link rel="stylesheet" href="styles.6ea28d52542acb20a4c6.css"><!docty ...

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Could converting a 47-byte JSON string into 340 MB be possible through JSON stringification?

var keys = [7925181,"68113227"]; var vals = {"7925181":["68113227"],"68113227":["7925181"]}; var temp = []; for (var i = 0; i < keys.length; i++) { temp[keys[i]] = vals[keys[i]]; } //alert(JSON.stringify(vals).length); alert(JSON.stringify(temp).le ...