What is the best way to loop through pairs of elements in a row using ngFor?

I am facing an issue with populating every two strings from an array in a row using ngFor. This is my current attempt:

<div class='row wow fadeInUp' *ngFor='let index of myArray; let i = index;'>
     <div class='col-md-6'>
         <md-card>
            <md-card-header>
               <md-card-title>
                 {{index}}
               </md-card-title>
             </md-card-header>
          </md-card>
     </div>
     <div class='col-md-6' *ngIf='i+1 < myArray.length'>
         <md-card>
            <md-card-header>
               <md-card-title>
                 {{myArray[i+1]}}
               </md-card-title>
             </md-card-header>
          </md-card>
    </div>
</div>

Whenever I add a new element, it duplicates the previous one and I cannot figure out why. How can I ensure that two elements are displayed in each row when using ngFor?

Answer №1

To easily skip every other index, you can simply check for even numbers (starting with 0 as the first index) when using *ngIf. Display the items with even indexes and indicate that the next item will be skipped (which have odd indexes):

<div class='row wow fadeInUp' *ngFor='let index of myArray; let i = index; let even = even'>
      <span *ngIf="even">
         <div class='col-md-6' >
             <md-card>
                <md-card-header>
                   <md-card-title>
                     {{myArray[i]}}
                   </md-card-title>
                 </md-card-header>
              </md-card>
         </div>
         <div class='col-md-6'>
             <md-card>
                <md-card-header>
                   <md-card-title>
                     {{myArray[i+1]}}
                   </md-card-title>
                 </md-card-header>
              </md-card>
        </div>
       </span>
    </div>

Check out this DEMO EXAMPLE

Answer №2

ngFor gives you access to odd and even, allowing for conditional display of items using ngIf.

<ul>
  <li *ngFor="let item of array; let even = even">
    <ng-container *ngIf="even">{{ item }}</ng-container>
  </li>
</ul>

However, it's recommended to handle this logic in your code rather than in the template. This approach is cleaner, more testable, and performs better.

evenItems = array.filter((_, index) => index % 2 == 0)

You can then iterate over these filtered items in your template.

<ul>
  <li *ngFor="let item of eventItems">
    {{ item }}
  </li>
</ul>

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

Modify information in formArray

Let's take a look at this setup I have: Model: export class MapDetailModel{ id: number; lat: number; lon: number; alt: number; long: number; angle: number; distance?: number; pendenza?: number; } Html: <div clas ...

Creating HTML code using an array of objects

My goal is to create HTML tags based on the object response shown below: "view": [{ "type": 'text', "depth": 0, "text": "This is a sample text" }] The objective here is to iterate through each type and add the corresponding HTML tags. &l ...

Encountered an issue with ionViewDidLoad: The property 'firstChild' cannot be read as it is null

While working on an Ionic 2 App with Angular2 and Typescript, I encountered an issue when trying to pass a JSON to map for markers. Here is the link to the gist containing the code snippet I am facing an error that reads: view-controller.js:231 MapPage i ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

Creating a Robust Next.js Build with Tailor-Made Server (Nest.js)

I'm in need of assistance with compiling/building my project using Next.js while utilizing a custom server. Currently, I have integrated Nest.js (a TypeScript Node.js Framework) as the backend and nested Next.js within it. The integration seems to be ...

Tips for retrieving additional values from a chosen variable in Angular 10

Here is an array I have: export const Glcode = [ { id: 1, Type: 'Asset', Name: 'Cash at Head Office', code: '10018' }, { id: 2, Type: 'Asset', Name: 'POS ACCOUNT ', code: '10432' }, { ...

The angular.json file contains a script and a styles property

After encountering issues with adding styles and scripts to my angular.json file, I discovered that neither Bootstrap nor other scripts were taking effect. It turns out there are two places where you can define scripts and styles in the angular.json file a ...

The error in Angular 6 is that the property 'controls' is not available on the type 'AbstractControl'

What happens when we use setvalue in a for loop? Everything seems to be running smoothly, but unfortunately an error is thrown: The property 'controls' is not recognized on the type 'AbstractControl'. In Angular 6, how can we resol ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...

Does the value of an Angular reactive form control only reflect what the user inputs?

I am working with a reactive form where I need to extract values and assign them to a variable defined in an interface. The form is populated using the Google Places API, which disables user interaction with all controls except for the initial address inpu ...

Ways to postpone the initialization of an Angular application in order to display animations

Incorporating a loading animation into my Angular application has been a recent enhancement. The animation is positioned between the <app-root> HERE </app-root> tags. To ensure proper display and functionality of this animation, I am looking t ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

Obtain the authorization token

To retrieve the token which contains abundant information, I'm utilizing the following method: getTokenSilently$(options?): Observable<string> { return this.auth0Client$.pipe( concatMap((client: Auth0Client) => from(client. ...

Vercel encountered issues with "validating code quality and type correctness" during deployment but was successful when performed locally

Running "next build" locally and "vercel build" both work smoothly. However, once deployed to vercel, the "Linting and checking validity of types" fails during the build process. It seems like TypeScript is stricter when building on vercel even with the sa ...

Creating a TypeScript class with methods to export as an object

Just dipping my toes into Typescript and I've encountered a bit of a challenge. I have a generic class that looks like this: export class Sample { a: number; b: number; doSomething(): any { // return something } } My issue ari ...

Function overloading proving to be ineffective in dealing with this issue

Consider the code snippet below: interface ToArraySignature { (nodeList: NodeList): Array<Node> (collection: HTMLCollection): Array<Element> } const toArray: ToArraySignature = <ToArraySignature>(arrayLike: any) => { return []. ...

Deactivate the button permanently upon a single click

In the project I'm working on, there is a verification page for e-mail addresses. When new users register, they are sent an e-mail with a link to verify their e-mail. If the link is not clicked within a certain time frame, a button appears on the page ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

A white background emerges when I select md-dropdown

Lately, I've been experiencing an issue on my website where a white background pops up whenever I click on a dropdown (md-select) in my form. Initially, it only happened with forms inside a modal, but now it's affecting dropdowns across the entir ...

Is it possible to declare two global variables with the same name in Angular?

There are two global variables that come from different third-party files with the same name. Previously, I would use them like this: declare var someVar; But now, how can I use both of these variables? declare var someVar; declare var someVar; Is th ...