Instead of removing a specific item, I am using the splice method to delete the last element in my array

I've run into an issue in my Angular 2 app while trying to remove an item from an array using the splice method. Whenever I click on the garbage icon next to an item, instead of deleting that specific item, it ends up removing the last item in the array. How can I modify my code to ensure that only the clicked item is deleted, rather than the last one?

Below is some information about my component:

  zipcodes = [
    { id: 3, zipcode: '75201', city: 'Dallas' },
    { id: 8, zipcode: '75205', city: 'Dallas' },
    { id: 1, zipcode: '77001', city: 'Houston' },
    { id: 2, zipcode: '78703', city: 'Austin' },
  ];

  deleteZip() {
    console.log('Delete zip clicked...');
    this.zipcodes.splice(this.zipcodes.indexOf(this.zipcode), 1);
  }

And here are the relevant parts of my component template/view:

<div *ngFor="let zipcode of zipcodes">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip()"><i class="material-icons">delete</i></span></div>

Answer №1

It is recommended to include the zipcode in your delete function

deleteZip(zipcode:any) {
    let index = this.zipcodes.indexOf(zipcode);
    if(index >= 0) {
        this.zipcodes.splice(index , 1);
    }
}

Next, update your template as follows:

<div *ngFor="let zipcode of zipcodes">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip(zipcode)"><i class="material-icons">delete</i></span></div>

Answer №2

It appears that this.zipcode cannot be located.
In the event that

this.zipcodes.indexOf(this.zipcode)
yields a result of -1 (indicating not found), executing:

this.zipcodes.splice(-1, 1)

Will consistently eliminate and retrieve the final item.

Answer №3

Hey Muirik,

It appears that the "this.zipcode" variable may not be the correct index to remove.

Have you tried passing in the specific index you want to remove like this:

<div *ngFor="let zipcode of zipcodes; let myIndex=index">{{zipcode.zipcode}} -- <span>{{zipcode.city}}</span><span class="delete-option" (click)="deleteZip(myIndex)"><i class="material-icons">delete</i></span></div>

This will send the index to your method, which should now look like this:

deleteZip(zipIndex: number) {
    this.zipcodes.splice(zipIndex, 1);
}

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

How to use jQuery to calculate the total sum of all values in a specific row

I have a table that contains inputs in each cell, except for one cell with the class of .total which displays the sum of each row in the table. I am trying to make it so that when any input in a row is changed, the sum updates dynamically for that specific ...

The Angular application is not showing the dynamic title tooltip for the font awesome icon

I am facing an issue where I cannot get the dynamic string to display in the tooltip of a font awesome icon, even though the ng-reflect-title does have a value. Can anyone help me figure out what I might be missing? Could it be something I'm overlook ...

Try out NextJS API middleware by running tests with Jest

I have a middleware setup in my NextJS API route, located at /src/middleware/validateData/index.ts. It's used to validate request data using a schema. import { NextApiRequest, NextApiResponse } from 'next'; import schema from './schema ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

I am experiencing issues with the jQuery function within my MVC Application

When working on my MVC application, I encountered an issue where the onclick function was not functioning as expected. @section Scripts{ <script src="~/Scripts/plugins/toastr/toastr.min.js"></script> <script> $(document). ...

Is there a way to invoke a function from a component that is neither a direct child nor parent component?

Module X let searchQuery = .... retrieveData(searchQuery); Module Y //implementing the use of Module X's parameter ...

Request to access embedded server with CORS (unchangeable) restrictions

When working with HTML4, I didn't encounter any issues creating an XmlHttpRequest to fetch an AJAX packet. However, as I'm moving on to HTML5, I've come across the term cors (which is new to me). Given that the server I'm dealing with i ...

Combine JSON data into groups based on two keys and calculate the overall count

Searching for a way to organize the JSON Array with 2 keys and calculate the counts of grouped object key using Javascript. Seeking a solution specifically in Javascript. Link to Reference Desired Outcome: the length of the counts object should be limit ...

Steps to activate or deactivate a button in Angular 2 depending on required and non-required fields

I am looking to have the Save button activated when the Placeholder value is set to 'Optional'. If the value is set to 'Mandatory', then the Save button should be deactivated and only become active if I input a value for that field. He ...

The precision of the Coinbase Pro API size is incredibly exact, with the smallest unit being 0.10000000

When utilizing the coinbase pro API for a sell request, I encountered the following issue: const sellParams = {"side":"sell","product_id":"DOGE-USD","type":"market","size":"135.5200 ...

Is there a way to create a Swiper slider similar to the one used in the App Store

I am looking to create a slider using Swiperjs similar to the carousel on the Apple App Store (seen on the Games tab). I attempted to implement it using Vue Swiper, a package for vue, as shown below: HTML code: <div id="app"> <h1>Slider< ...

Unable to install Typescript using npm

I recently started a tutorial on Typescript and wanted to install it globally using npm. npm i typescript -g However, I encountered an issue where the installation gets stuck on the first line and displays the following message: (⠂⠂⠂⠂⠂⠂⠂⠂ ...

Exploring an Array in Javascript derived from a PHP Array

I have a PHP variable named $TillArray that contains an array. I am trying to pass this array to a Javascript function in order to display an Alert message for each item within the array. Below is the code I have been using: <script type="text/javasc ...

Is there a way to reach a different function within the value of the react Context.Provider?

Right now, I am learning how to utilize the react context API. Within my react Provider class, I have some state data and functions stored in the value={}. But I am curious, how can I call a function inside this value from another function within the same ...

Encountering difficulties accessing functions from apollo-server-express

I have been following a tutorial and attempting to launch the node server, but I am unable to import these functions from the Apollo package const {graphqlExpress, graphiqlExpress} = require('apollo-server-express'); // importing functions here ...

The collaboration of Nodemon and Redwood-Broker

I have been running Nodemon in my express app without any special configuration. In my package.json file, I only have the following: "scripts": { "start:dev": "nodemon app/app.js" } ... Everything runs smoothly until I make changes and Nodemon attempts ...

Is there a way to send push notifications to a designated user on an iOS device using Firebase, without relying on APN?

In my Angular project for a kindergarten portal, teachers post updates on what students are doing throughout the day. When a new article is published for a specific child, I want to send a push notification to their parent's iOS device. A former empl ...

An issue with event listeners in Vue 3 and Pixi.js arises when working with DisplayObjects that are either created as properties of classes or inherited from parent classes

Utilizing PIXI js in conjunction with Vue 3 (see code snippet below) Due to the consistent pattern of most graphics with varying behaviors and properties, we opted for an OOP approach with TypeScript to prevent code duplication. However, following this app ...

Using Ajax to populate two dropdown menus by utilizing the selected value from a third dropdown menu

I have an HTML page that includes 3 drop-down boxes. Whenever I make a selection in one of the boxes, the chosen value is sent to the server, and the server should return the values for the other 2 drop-down boxes. How can I dynamically populate the other ...

Error in jQuery Ajax post request caused by a keyword in the posted data

I understand why the post is failing, but I'm at a loss on how to fix it and I haven't been able to find any solutions online. I am removing references to jEditable in an attempt to simplify things, as this issue occurs even without the jEditable ...