remove item from stored array in angular 2

前端 未结 11 1887
长发绾君心
长发绾君心 2020-12-23 02:34

I want to remove an item from a stored array in angular 2, with Type Script. I am using a service called Data Service, the DataService Code:

export cl         


        
相关标签:
11条回答
  • 2020-12-23 03:03

    Use splice() to remove item from the array its refresh the array index to be consequence.

    delete will remove the item from the array but its not refresh the array index which means if you want to remove third item from four array items the index of elements will be after delete the element 0,1,4

    this.data.splice(this.data.indexOf(msg), 1)
    
    0 讨论(0)
  • 2020-12-23 03:10

    This can be achieved as follows:

    this.itemArr = this.itemArr.filter( h => h.id !== ID);

    0 讨论(0)
  • 2020-12-23 03:11

    I think the Angular 2 way of doing this is the filter method:

    this.data = this.data.filter(item => item !== data_item);
    

    where data_item is the item that should be deleted

    0 讨论(0)
  • You can delete the data from array

    this.data.splice(index, 1);
    
    0 讨论(0)
  • 2020-12-23 03:22

    Sometimes, splice is not enough especially if your array is involved in a FILTER logic. So, first of all you could check if your element does exist to be absolute sure to remove that exact element:

    if (array.find(x => x == element)) {
       array.splice(array.findIndex(x => x == element), 1);
    }
    
    0 讨论(0)
  • 2020-12-23 03:23

    Don't use delete to remove an item from array and use splice() instead.

    this.data.splice(this.data.indexOf(msg), 1);
    

    See a similar question: How do I remove a particular element from an array in JavaScript?

    Note, that TypeScript is a superset of ES6 (arrays are the same in both TypeScript and JavaScript) so feel free to look for JavaScript solutions even when working with TypeScript.

    0 讨论(0)
提交回复
热议问题