Removing a row will always result in the deletion of the final row, as the index is returned as

In my Angular application, I have a Reactive Form with a feature that allows users to add or remove rows. Each row has its own delete button. However, there is an issue where clicking on the delete button for a specific item results in the last row being removed instead. Upon debugging, I noticed that the index returned is -1, indicating that the last item will be deleted.

delete_communityList_row(id) {
  const index = this.Form.value.communityList.indexOf(id);
  this.Form.value.communityList.splice(index, 1);
}

Despite the delete button correctly returning the "id" of the clicked row, I am unsure why the deletion is not working as expected. The console.log output shows an array of objects.

https://i.sstatic.net/gDs1E.png

Answer №1

Within your code, the communityList property contains a collection of objects and you are attempting to check for the index of an id (likely a string or number) that is not present in the array as an element (it is a property value of the object), resulting in it always returning -1. According to the documentation on Array#splice, if the start value is negative, it counts from the end, such as array.length - n (-1 represents the last index).

You can obtain the index by checking the property value using the Array#findIndex method, which iterates through the array and returns the index when the callback function evaluates to true.

const index = this.Form.value.communityList.findIndex(o => o.id === id);

Updated code:

delete_communityList_row(id) {
  const index = this.Form.value.communityList.findIndex(o => o.id === id);
  if(index !== -1) this.Form.value.communityList.splice(index, 1);
}

Note: If you are calling this method from the template (generated using *ngFor), consider passing the index instead of the id for simplicity.

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

Best practice for encapsulating property expressions in Angular templates

Repeating expression In my Angular 6 component template, I have the a && (b || c) expression repeated 3 times. I am looking for a way to abstract it instead of duplicating the code. parent.component.html <component [prop1]="1" [prop2]="a ...

Navigating through child routes in Angular can be tricky, especially when dealing with unknown routes

I'm having some trouble with routing today. I have a collection of components each associated with a unique route. I am trying to include a 'PageNotFoundComponent' for any incorrect route in both the parent and child components. Let me expla ...

Searching through an array of objects with ng2-completer does not yield any search results

Having some trouble with the ng2-completer plugin when trying to enable auto-complete functionality in a search box. The issue arises when attempting to use an array of objects instead of just strings, resulting in a 'No Results found' message. E ...

Uncovered requirement for the selectSignal in an isolated module

While trying to utilize selecctSignal in a standalone component, I encountered a runtime error: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(Standalone[AllTablesHeadComponent])[signal -> signal -> signal -> signal]: N ...

What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following: import multipleActionObject from page; it("should be able to perform multiple operations", () => { multipleActionObject.chooseIndex(4).setValue(10); } Inste ...

custom tooltip for ngx-charts

I am currently working on implementing a customized tooltip for heatmap cells using ngx-charts-heat-map. The challenge I'm facing is that the data I want to display does not fall under series, value, or name. It actually comes from a different propert ...

Refreshing a page in Angular 2 using webpack may sometimes lead to the index.html file loading without any styling or

I'm having trouble with my Angular 2 project. Every time I refresh the page or the HRM does, it redirects to index.html (or '/') without injecting the html code and webpack head-config.common.js properly. Additionally, I noticed that the web ...

Issue with IE11 compatibility in Angular2 (AngularQuickStart version 2.4.0) due to syntax error

Encountering an error in the browser console when attempting to run my Angular2 app on IE11. The error "Недопустимый знак" translates to unacceptable symbol. https://i.stack.imgur.com/0mHBC.png Here is a snippet of my index.html: <!DO ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

The NestJS Service/Validator encounters a TypeError when trying to access properties of undefined, specifically when attempting to read 'get'. This error occurs when the injected objects are not available for use within

Exploring the NestJS Validator Service Implementation @ValidatorConstraint({ async: true }) @Injectable() export class IsValidWorkingHourConstraint implements ValidatorConstraintInterface { private readonly WORKING_HOUR_START: number; private readonly ...

Differences between Strings and Constants in React While Using Redux for Action Types

In the Redux guide, it is suggested to define strings constants for Redux action types: const FOO = 'FOO'; const BAR = 'BAR'; dispatch({ type: FOO }); It's worth noting that most concerns raised are relevant to untyped JavaScrip ...

What could be causing the Timeout error to occur in my Jasmine unit test for the HTTP interceptor?

I've been facing challenges with unit testing my interceptor since yesterday afternoon. Despite following multiple tutorials and Stack Overflow answers, I have managed to write what seems like the best code so far. However, I'm encountering an er ...

How to use CSS to add a pseudo element to a table and position it outside of the parent's boundaries on the left

I am currently utilizing the "ag-grid" data-table library (along with Angular 2, although the framework is not crucial) which highlights a selected row (using the default class .ag-row) by adding the class .ag-row-selected to it. Each row contains numerous ...

Universal NestJS GraphQL Guard

I am currently working on implementing a global guard to ensure that all requests receiving MUTATIONS from graphql require the token in their headers by default. The code below successfully achieves this: graphql-context-get-token.guard.ts import { ...

Utilizing Angular's Dynamic Component Import and Loading capabilities

Looking to develop a portal that can dynamically load Angular components without the need for explicit imports. I've heard about using ComponentFactoryResolver for this purpose, but hoping to have the ability to store components in separate files or r ...

What is the reason behind the return type of 'MyType | undefined' for Array<MyType>.find(...) method?

Currently, I am in the process of developing an Angular application using TypeScript. As part of this project, I have defined several classes along with corresponding interfaces that align perfectly with their respective properties: Map: export class Map ...

Arithmetic operations cannot be performed on the values generated by an observable interval

I am attempting to multiply interval emitted values by 10 in order to create a resulting stream like: 10, 20, 30 ... However, I am facing an issue where the compiler throws an error when trying to use the map method. const numbers$ = Observable.interval(1 ...

Is there a way to retrieve the type of a generic class in JavaScript?

class Alpha { static construct<T extends typeof Alpha>(this: T): InstanceType<T> { const v = new Alpha(); return v as InstanceType<T>; } } class Beta extends Alpha {} const x = Alpha.construct(); // generates Alpha const y = ...

What is the best way to determine the width and height of text within a TextArea using JavaScript in an HTML document

Imagine this scenario: https://i.stack.imgur.com/cliKE.png I am looking to determine the size of the red box within the textarea. Specifically, I want to measure the dimensions of the text itself, not the dimensions of the entire textarea. The HTML code ...

Bring in Event Types from React using TypeScript

Is there a way to import Event Types from React and use them in Material-ui? Specifically, I am looking for guidance on how to import KeyboardEvent so that it can be utilized for onKeyDown callback type annotation. I have examined the .d.ts file of Mater ...