Delete a specific element from an array using a specified criteria

I'm attempting to remove a specific item from an array based on the selected option. To better understand, take a look at this code:

component.html

<fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto">
    <fnd-option *ngFor="let p of agreementfilter?.landingPageTypes" [value]="p.id">{{p.description}}</fnd-option>
</fnd-extended-select>

Component.ts

  deleteMsg() {
    this.agreementfilter.landingPageTypes.splice(1, 1);
  }

Essentially, when I click the button to delete the item, only the FIRST object in the array gets removed.

What I Want: Remove the item that I have selected from the array.

What are my options for solving this issue?

Appreciate your assistance!

Answer №1

component.html

<fnd-extended-select label="Product Type:" [(ngModel)]="selectedType" 
 name="producttype">
<fnd-option *ngFor="let type of productFilter?.productTypes; let i = index" 
  [value]="i">{{type.description}}</fnd-option></fnd-extended-select> <button (click)="removeType(selectedType)"></button>

component.ts

 selectedType;

  public removeType(id: number) {
    // find index of item to be removed and delete it from the array
    this.productTypes.splice(id, 1);

    // display updated array in console after deletion
    console.log('productTypes: ', this.productTypes);
  }

public change(id) {
  // update select option and store index in a variable
  this.selectedType = id;
  console.log(id);
}

view example at stackblitz

Answer №2

To implement this, you can include a click event and pass the index as a parameter.

Here is an example in Component.html:

 <fnd-extended-select label="Product Type:" [(ngModel)]="landingType" 
     name="producttype">
    <fnd-option *ngFor="let p of agreementfilter?.landingPageTypes; let i = index" 
      [value]="p.id" (click)="removeItem(i)">{{p.description}}</fnd-option>
  </fnd-extended-select>

And in your Component.ts file:

 removeItem(index) {
   this.agreementfilter.landingPageTypes.splice(this.agreementfilter.landingPageTypes.indexof(index), 1);
}

Answer №3

The correct solution was shared by @Nenad Radak within the comments section of his answer.

I saved the value in my component and then retrieved it when the button event occurred.

code:

temporary:string;

<fnd-extended-select label="Product Type:" [(ngModel)]="landingType" name="producttype">
  <fnd-option *ngFor="let p of agreementfilter?.landingPageTypes; let i = index" (click)="tempor(i)" [value]="p.id">{{p.description}}</fnd-option>
</fnd-extended-select>


 tempor(index){debugger;
   this.temporary= index
 }
  deleteMsg() {

    this.agreementfilter.landingPageTypes.splice(this.temporary, 1);
 }

Answer №4

To remove a specific item from an array, utilize the delete message function by passing in the ID of the item you wish to delete. Next, find the index of that item within the array using findIndex. Once you have located the index, leverage the splice method to eliminate the entry at that position.

For a practical demonstration, I have created a Stackblitz example: https://stackblitz.com/edit/angular-icpmqo

public deleteMessage(id: number) {
    this.pageTypesArray.splice(this.pageTypesArray.findIndex((page) => page.id === id), 1);
}

Answer №5

If you are looking to remove an item from a list, you can do so by locating its index. Let's say the item you wish to delete is the one you have selected (which in this case is referred to as 'landingType').

      deleteMsg() {
        this.agreementfilter.landingPageTypes.splice(this.agreementfilter.landingPageTypes.indexOf(landingType), 1);
}

Here's an example:

    var months = ['Jan', 'March', 'April', 'June'];
      console.log(months);
    // expected output: Array ['Jan','March', 'April', 'June']

     console.log(months);
     months.splice(months.indexOf('April'), 1);
   // expected output: Array ['Jan','March', 'June']

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

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

ag-grid Server Side pagination function to enable independent setting of last row

Currently, I am utilizing ag-grid, Angular 7, and implementing a server-side datasource with pagination. In my API setup, I initiate two requests: the first request provides the total number of items in the table, while the second fetches the data for the ...

What is the method to access the value of a different model in ExpressJs?

I am working on a MEAN stack and have a model for employee information. I want to include the store name where they will work from a separate stores model. Can you review my approach below? Employee Model: var mongoose = require('mongoose'); va ...

404 Error: Unable to Locate Socket Io

I'm currently working on implementing a chat feature in Angular 2 using Socket IO, following this tutorial. However, I encountered an error message during a test on the server: GET http://localhost:3000/socket.io/?EIO=3&transport=polling& ...

"Encountering an error when trying to access undefined property in templates

The content displayed in my component template is not what I expected when using @Output to pass an object from a parent container. While attempting to bind {{selectedMovDetail|json}} in the template, the output shows as { "name": "The Walking Dead","rati ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

Updating the data attribute of an object in HTML using Angular

I am trying to embed a PDF viewer inside a component. In order to dynamically update the PDF document within a sanitizer, I need to use an attribute with []. This works fine with images. <img src="assets/pic.jpg"/> <img [src]="'assets/pi ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this ...

What exactly do Dependencies mean in Angular?

As a beginner in Angular, the concept of dependencies has come up several times during my learning process. Despite my efforts to search for a clear definition of Dependencies in Angular on Google, I have been unsuccessful. Could someone please provide a ...

I prefer to have static modules generated on the home page rather than dynamic ones

As a newcomer to Angular, I am facing an issue with dynamic modules in my project. Currently, all modules are being generated when I run the project, but I only want to generate the login page module. Below is a screenshot and the code from the app.routing ...

Prevent the Vue page from loading until the data has been fetched successfully

I'm in the process of finding a way to prevent my page from loading until my fetch task is completed. I'm facing some issues that need to be addressed: I have to re-fetch the data each time because I can't reuse the same data. (Changing vie ...

There is no throttleTime function available in Angular 6 within Rx Js

Currently, my Angular 6 project is utilizing angular/cli": "~6.1.5 and rxjs": "^6.0.0. As a newcomer to Angular 6, I decided to dive into the official documentation to enhance my understanding. Here's a reference link I found useful: http://reactivex ...

MasterNG - Submitting form details and uploading files with a button press

Our Angular project involves a form with various form fields along with PrimeNG FileUpload, and our goal is to send the form data along with the selected files in one go. Despite researching the documentation and numerous examples online, we couldn't ...

What is the best way to transform RestApi object information into an Array?

How can I transform the data fetched from PokeApi into an Array that can be used in Angular? When trying to assign it to an Array directly in HTML, it gives an error due to its Object return type. getPokemonDetail(index) { return this.http.get(`${this ...

What causes the entire set of dynamically created cards to collapse when using the toggle collapse button in ngb-bootstrap's Collapse control?

I am currently implementing the ngb-bootstrap collapse feature in my Angular 9 application. Incorporating the ngb-bootstrap collapse functionality within a Bootstrap card, I have multiple cards being generated. Each card is equipped with a collapse button ...