Difficulty with Iterating through Items in Angular HTML with *ngFor

Having an issue with *ngFor. It seems like the index in my tab object "joueurClassement" is not in the correct number sequence. The picture below illustrates this problem, where it works fine when the indexes are 0,1,2,3,4.

In my HTML =>

  <tbody>
                <tr *ngFor ="let player of joueurClassement; let i = index">
                <td>{{ player.nom }}</td>
                <td>{{ player.prenom }}</td>
                <td>{{ player.point }}</td>
                <td>{{player.victoire}}</td>
                <td>{{player.defaite}}</td>
                <td>{{player.nbdejeu}}</td>
                </tr>
            </tbody>

*ngFor Resolution

However, if the index numbers are not in the correct sequence (not 0,1,2,3,4), then the ngFor fails to display properly as shown in the following picture. My object "joueurClassement" does not appear on the screen. *ngFor Issue

Answer №1

It seems like the issue you're facing is related to receiving sparse arrays with non-consecutive indices.

To resolve this, try implementing the following template:

<table>
  <tbody>
    <ng-container *ngFor="let keyValuePair of joueurClassement | keyvalue; trackBy: trackKeyValuePair">
      <tr *ngIf="keyValuePair.value as player">
        <td>{{player.nom}}</td>
        <td>{{player.prenom}}</td>
        <td>{{player.point}}</td>
        <td>{{player.victoire}}</td>
        <td>{{player.defaite}}</td>
        <td>{{player.nbdejeu}}</td>
      </tr>
    </ng-container>
  </tbody>
</table>

Additionally, I included a trackBy function for better performance. Here's how it can be implemented:

class MyComponent {
  trackKeyValuePair(_index, keyValuePair): number {
    return keyValuePair.key;
  }
}

You can view the solution in action on StackBlitz by clicking here.

Answer №2

This bug seems to occur for unknown reasons, but if you simply want to use *ngFor without specifying an index, you can do it like this:

<tbody>
            <tr *ngFor ="let player of joueurClassement">
            <td>{{ player.nom }}</td>
            <td>{{ player.prenom }}</td>
            <td>{{ player.point }}</td>
            <td>{{player.victoire}}</td>
            <td>{{player.defaite}}</td>
            <td>{{player.nbdejeu}}</td>
            </tr>
        </tbody>

You can skip specifying the index in *ngFor as it behaves similar to a Foreach loop.

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

Recursive type analysis indicates that the instantiation of the type is excessively deep and may lead to potential infinite loops

In the process of developing a Jest utility, I have created a solution where an object mock is lazily generated as properties are accessed or called. Essentially, when a property is invoked like a method, it will utilize a jest.fn() for that specific path ...

How do I retrieve a specific svg element in Angular among multiple elements?

I recently delved into learning Angular for a new project. One of my main objectives was finding a way to dynamically alter the styles of SVG elements. This led me to utilizing ViewChild and ElementRef. Here is an example from the HTML: <svg><g ...

Display the list of cities associated with the country chosen in the form

I am currently working with the repository found at https://github.com/country-regions/country-region-data/blob/master/data.js to create a mapping of countries and their related cities. I'm seeking guidance on how to achieve this task effectively. My ...

Looking to establish combinations in typescript? The answer lies in utilizing a discriminated union

I've been working with Typescript and I'm curious if it's possible to specify the valid combinations of input for a function. Below is a simplified version of the code: interface ActionType { type: string, payload: { count?: ...

Experimenting with key directive in the newest version of Angular (9)

I'm currently testing a directive, but I am facing an issue where the length of the value in the directive is always undefined. What could be causing this problem? @Directive({ selector: '[evAutoTab]' }) export class EvAutoTabDirective { ...

CORS problem arises specifically in NestJS and Vercel when sending POST requests

GET requests are functioning correctly, however, I am encountering issues with SWR when attempting to make POST requests to submit data to Firebase. The goal is to mutate state based on these requests, but I am unable to successfully perform POST requests. ...

Is it possible to use a component created in the newest version of Angular in apps developed with older versions of Angular?

I am interested in developing a component using the most recent version of Angular. However, my intention is to use this component in two distinct Angular applications - one created with Angular 6 and another with Angular 10. Is it feasible to achieve this ...

Choose the AuthGuard category in real-time

My application intends to employ two distinct authentication strategies - one for users accessing via a browser and another for the public API. A specific header will be set for browser users, allowing my app to determine the appropriate auth strategy base ...

Strategies for preventing profanity in Typescript within Nuxt 2 implementation

implement user authorization functionality create the Auth class for authentication handling import type { Context } from '@nuxt/types'; export class Auth { public ctx: Context; constructor(ctx: Context) { t ...

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

What is the impact on active subscriptions when the browser is closed or refreshed?

Within the app component (the root component) of an Angular application, I have a few subscriptions set up. Since the app component remains active and is never destroyed until the application is closed, the ngOnDestroy method of the app component does not ...

The overall package size post transitioning to standalone versions and incorporating lazy loading

Initially, my app had a setup where each component had its own module and lazy-loading was implemented. This resulted in a main.js bundle size of 2mb. However, after converting to standalone components with lazy loading, the bundle size increased to 4mb. ...

Ensuring Consistency of Values Between Child and Parent Components

Is there a way to ensure that the value of submitted in the child component always matches the value of submitted in the parent component? Appreciate any help! @Component({ selector: 'child-cmp', template: ` child:{{submitted}} ...

Encountering a 404 error while attempting to test a contact form on a Next.js website using a local server

Trying to test a contact form in Next.js where the data is logged but not sent to the API due to an error. "POST http://localhost:3000/app/(pages)/api/contact/route.tsx 404 (Not Found)" Troubleshooting to identify the issue. [directory setup] ...

Acquiring a second access token in Java for the Graph API using an OIDC-compliant token can be achieved through the OBO flow method

Utilizing the angular-oauth2-oidc library within Angular allows me to login through the PKCE Authorization Flow, followed by passing the token to my backend in order to secure my custom API. The Spring boot backend functions as the oauth2 Resource Server ...

Looking to effortlessly move and arrange items with ng2-drag-drop in Angular 2?

I have encountered a problem with the ng2-drag-drop library. I am trying to drag and drop items from one div to another, and then freely move the dropped item within the droppable area. One issue I'm facing is that when I drop my draggable item in th ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

Protected Node.js API paths

Recently, I was developing a login with OTP feature for my app. The front-end is being built using Angular and the back-end on ExpressJs. However, I have been struggling to find a way to secure the API. Every time I test the API using Postman, it works per ...

What is the best way to modify onClick events for elements in Ionic v4 with React?

Is there a way for me to interact with a button or IonItemSliding in order to alter the text or color of an element? <IonItemOptions side="start"> <IonItemOption color="success">Yes</I ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...