Generating duplicate IDs in ngForOf loop in Angular

My current setup uses ngForOf to display dates, with each date having an id property which is basically its index + 1. These dates are stored as objects in an array and each date is represented by a component instance.

The issue I am facing with ngForOf is that whenever I remove a date from the list, the entire DOM refreshes and new IDs are reassigned.

<app-date *ngFor="let date of dates | callback: filterDates; index as i" (delete)="del(i)"></app-date>

The Dilemma

When I use the "delete" function, I do not actually splice/remove the date from the array; instead, I set the action property of the date to "deleted". This saves me from making HTTP requests to delete each date from the backend database.

Once the action is set to "deleted", the date disappears from the DOM but remains in the array. Therefore, during the next DOM refresh, new IDs are assigned leading to duplicate IDs in the array. This causes issues such as the inability to delete dates with the same ID.

I did attempt to update the ID of the date on every deletion event, but this also caused problems within the array.

Key Point

While I have some knowledge about trackBy, I am unsure how to implement it to resolve this particular issue. My search for similar problems online has been unsuccessful so far.

Thank you.

Answer №1

I managed to successfully resolve the issue at hand.

  • Scenario

The situation involved dealing with two arrays: one being the dates array used for rendering dates, and the other array containing the DOM elements representing each date displayed on the screen. In Angular, the framework does not consider the id or index assigned to each date in the dates array within the component.ts file. Instead, it tracks individual elements in the ngFor loop based on their index within the DOM array. As a result, this DOM array undergoes changes during add/remove operations.

The error I encountered was using the index of the DOM array as the id for the date. This led to duplications in the id values within the array whenever dates were removed without actually deleting or splicing them from the array.

  • Resolution

To address this issue, it is advisable to implement a separate function for generating unique IDs or simply utilize a property that increments with each pushDate() operation. While this may mitigate the problem of duplicate ids to some extent, Angular's reliance on the index within the DOM array remains unchanged. Therefore, to delete a specific date, it is essential to know its index within the DOM array.

<app-date *ngFor="let date of dates | callback: filterDates; index as i" [id]="dateID" (delete)="del(i, $event)"></app-date>

Subsequently, the (delete) function will provide a string indicating the date to be deleted, such as 2020-8-15. This date, coupled with the action attribute of the respective date, facilitates the identification of the designated date for deletion using the following approach:

getArrayIndex = (index: number, date: string): number => {
    for (let i = 0; i < this.dates.length; i++) {
        if(i == index && date == this.dates[i]['date']) {
            if(this.dates[i]['action'] == 'deleted') {
                return this.getArrayIndex(i + 1, date);
            }
            else {
                return i;
            }
        }
        else if(i == index && date != this.dates[i]['date']) {
            return this.getArrayIndex(i + 1, date);
        }
        else if(i != index) {
            continue;
        }
        else {
            return i;
        }
    }
}

del = (num: number, event: string) => {
    let i = this.getArrayIndex(num, event);
    this.dates[i]['action'] = 'deleted';
}

In essence, the del function locates the correct index of the specified date within the dates array using getArrayIndex(), subsequently marking the action property of that particular date object as "deleted".

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

Encountered "Function undefined error when invoking within a map in TypeScript"

In my function, there is a map that looks like this: mainFunc(){ // other logics data.map(function (item) { item.number = Math.round(item.number); item.total = item.last - item.first; item.quantity= item?.quantity ? quantityRange(ite ...

Issue encountered when trying to redirect after user creation on the backend

To persist a user, I use this method inside form-registrar-usuario.component: registrarUsuario(){ const role = this.route.snapshot.params["role"] if(role == "Proponedor"){ this.autorizacionService.registrarUsuario( role, thi ...

Removing the outer array of objects can be achieved by using a variety of

My goal was to eliminate the outer array of objects. I attempted to achieve this by using the code below: export class AppComponent implements OnInit { name = 'Angular'; EmployeeData=[ {"name": [{ "grade": &quo ...

Tips for showcasing information from a nested array and modifying data in an Angular application

I am in the process of developing a cutting-edge Angular application to monitor my fitness workouts at the gym. Enclosed within this array are the diverse exercise names, repetitions, sets, weights, and more that constitute each workout: workoutExercises ...

reconfigure components by resetting settings on a different component

In the interface, I have a section that displays text along with a unique component titled FilterCriteriaList. This component includes custom buttons that alter their color when clicked. My goal is to reset the settings in the FilterCriteriaList component ...

What is the importance of having a reference path for compiling an AngularJS 2 project using gulp-typescript?

I wanted to modify the Angular Tour Of Heros project to utilize gulp from this Github Repository. This is the gulpfile.json file I came up with: const gulp = require('gulp'); const del = require('del'); const typescript = require(&apo ...

Embracing the "export ... from" feature in the TypeScript compiler

Can the tsc compiler handle this particular export statement? export {PromiseWrapper, Promise, PromiseCompleter} from 'angular2/src/facade/promise'; Your assistance is greatly appreciated! ...

Oops! The program encountered an issue where it was unable to access the properties of an undefined variable, specifically while trying to

When creating a custom validation function in Angular, I encountered an issue where using a variable within the validation would result in an error: "ERROR TypeError: Cannot read properties of undefined (reading 'file')". This occurred when chang ...

One potential solution for fixing the error in GetRepository of TypeORM is to check for undefined properties before attempting to access them. This error typically occurs when trying to read properties of an undefined

[Nest] 171 - 08/31/2022, 8:35:42 PM ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'getRepository') tenant-node | TypeError: Cannot read properties of undefined (reading 'getRepository') tenant-node | at Instance ...

Angular date selection with a range of plus two days, factoring in the exclusion of weekends

I am currently using a mat date picker range with specific logic. The minimum date that a user can select on the calendar is set to + 2 days. For example, if today's date is July 20, 2022, the minimum selectable date would be July 22, 2022. However, ...

Angular version 2 has a directive called "ng2-nvd3" which seems to be undefined

I am attempting to incorporate a graph similar to the one shown in this Plunker example: Plunker Here is the corresponding code hosted on GitHub: GitHub However, I encountered an error: Uncaught (in promise): Unexpected directive value 'undefined ...

Having trouble resolving modules after generating tsconfig.json?

I recently added a tsx component to my next.js 13 project following the documentation. After creating the required tsconfig.json file, I encountered module not found errors when running npm run dev: $ npm run dev > [email protected] dev > n ...

The command "tsc" was not found in this bash session

Currently, I am using a MAC and attempting to set up TypeScript. I followed the installation process by running sudo npm install -g typescript and received the following output: Password: /Users/<myuserid>/node/bin/tsc -> /Users/<myuserid& ...

Implementing a custom type within a generic function

Struggling with a particular problem, I am trying to figure out whether it is possible to pass a custom type or if only native TypeScript types (such as string and number) can be passed into a generic type implementation for an interface: type coordinates ...

Icon appearing outside the button instead of inside

Here's a button I'm working with: <button class="glyphicon glyphicon-option-horizontal" (click)="myFuncion()"></button> Recently, I updated my bootstrap library from version 3 to 4.2.1 and now the icon is no longer visible. I' ...

NgRx Action Payload fails to trigger Effect, but no error messages are generated

I've exhausted all resources on Stack Overflow and still can't seem to figure this out. The issue lies in passing a payload into the 'GetUser' action. My intention is for this payload to go through the effect, and eventually be sent v ...

Using Angular2's NgFor Directive in Components

I am faced with the challenge of converting a tree-like structure into a list by utilizing components and subcomponents in Angular 2. var data = [ {id:"1", children: [ {id:"2", children: [ {id: "3"}, {id: "3"}, {i ...

Accessing Promise.all in the rejection function is not allowed

I have a service that retrieves data, and I make 5 calls to it with different parameters to retrieve various datasets. When the function is successful, everything works fine. However, in case of failure for any of the 5 calls, I need to handle it differen ...

What's with all the requests for loaders on every single route?

I'm in the process of setting up a new Remix Project and I'm experimenting with nested routing. However, no matter which route I navigate to, I keep encountering the same error: 'You made a GET request to "/", but did not provide a `loader` ...

Creating a type declaration for an object by merging an Array of objects using Typescript

I am facing a challenge with merging objects in an array. Here is an example of what I am working with: const objectArray = { defaults: { size: { foo: 12, bar: { default: 12, active: 12 } }, color: {} } } ...