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

E6 arrow functions simplify the process of condensing an array of objects into a single object

Here is an array that I have: a=[{'test':1,'test2':'2'},{'test':3,'test2':'4'}] My goal is to reduce this array into a single object This is the expected output {1:2,3:4} I attempted the foll ...

Tips for converting numerical values in a JSON object to strings within a TypeScript interface

{ "id": 13, "name": "horst", } in order to interface A { id: string; name: string; } When converting JSON data of type A to an object, I expected the conversion of id from number to string to happen automatically. However, it doesn' ...

What is the most reliable method for converting a 32-bit unsigned integer to a big endian byte array?

Looking for a simple and reliable method to convert an unsigned integer into a four-byte-array in big endian format, with padding if necessary? Take a look at this example: Input value: 714 Output: Resulting byte array [ 0xca, 0x02, 0x00, 0x00 ]; By the ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...

Error encountered while upgrading to Angular 5: splitHash issue

Currently in the process of transitioning from Angular 4.x to 5.x, I have encountered the following error: main.81bcdf404dc22078865d.bundle.js:1 Uncaught TypeError: i.splitHash is not a function at Object.t.parseUrl (main.81bcdf404dc22078865d.bundle.js:1) ...

Can a Vue application be made type-safe without the need for transpilation?

Is it possible for Vue to be type-safe when used without transpilation (without a build step) as well? Can TypeScript or Flow be used to ensure type safety? ...

Guide for registering to modifications of a single key within a form group in Angular 2

I am facing an issue with my userForm group that consists of keys name, email, and phone. I have implemented an onValueChanged function to validate these fields whenever they are changed. However, the validation runs every time even if the field has not ...

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}} ...

Whenever I attempt to make changes to the React state, it always ends up getting reset

Currently, I am attempting to utilize Listbox provided by Headless UI in order to create a select dropdown menu for filtering purposes within my application. However, the issue I have encountered is that whenever I update my "selectedMake" state, it revert ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Switching over to Typescript: Sending mapped properties

I'm having trouble converting my React.JS script to TypeScript. I need assistance in creating a drop-down navigation bar on my website. Here's a snippet from my Header.tsx file: The error message Property 'onClick' does not exist on t ...

Issue with Readonly modifier not functioning as expected in Angular/Typescript

My goal is to create a component property that is read-only. However, I am facing an issue where the readonly modifier does not seem to have any effect. View example on stackblitz According to the documentation, once I initialize the cars property in the ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

Angular 11.0.3 displaying ngClass issue (Unable to bind ngClass as it is not recognized as a property of div)

While working on an angular project, I implemented a light and dark theme using mat-slide-toggle to switch between themes. The theme is stored as a boolean called isDark in a Behavioral Subject service. There are two lazy-loaded modules - one for the home ...

Verify the presence of identical items in the array

I have been attempting to identify any duplicate values within an array of objects and create a function in ES6 that will return true if duplicates are found. arrayOne = [{ agrregatedVal: "count", value: "Employee Full Name" }, { agrrega ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Leveraging Angular for Remote Configuration Management

How is everything going with you? I'm attempting to retrieve a configuration that I previously set up in Firebase's remote config using my Angular 15 application. The specific configuration is called "AllowedUsers." Here is the image of th ...

Disabling an anchor using the 'disabled' property is proving to be a challenge for me

I'm attempting to dynamically enable or disable an anchor element based on the user's role. So far, I've tried a few different methods: document.getElementById('myBtn').disabled = true; However, this returns an error: The propert ...

Is it necessary to include explicit overlapping imports in Angular if they are already imported in the parent component?

Do you think the title needs clarification? Feel free to offer suggestions. I've noticed that my design components are ending up with a lot of imports. Some of these imports are duplicated in the component that is importing them. I'm managing to ...