137

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 class DataService {

    private data: string[] = [];

    addData(msg: string) {
        this.data.push(msg);
    }

    getData() {
        return this.data;
    }

    deleteMsg(msg: string) {
        delete [this.data.indexOf(msg)];
    }
}

And my component class:

import {Component} from '@angular/core'
import {LogService} from './log.service'
import {DataService} from './data.service'

@Component({
    selector: 'tests',
    template:
            `
        <div class="container">
            <h2>Testing Component</h2>
            <div class="row">
                <input type="text" placeholder="log meassage" #logo>
                <button class="btn btn-md btn-primary" (click)="logM(logo.value)">log</button>
                <button class="btn btn-md btn-success" (click)="store(logo.value)">store</button>
                <button class="btn btn-md btn-danger" (click)="send()">send</button>
                <button class="btn btn-md " (click)="show()">Show Storage</button>
                <button (click)="logarray()">log array</button>
            </div>
            <div class="col-xs-12">
                <ul class="list-group">
                    <li *ngFor="let item of items" class="list-group-item" #ival>
                        {{item}}
                        <button class="pull-right btn btn-sm btn-warning" (click)="deleteItem(ival.value)">Delete
                        </button>
                    </li>
                </ul>
            </div>
            <h3>{{value}}</h3>
            <br>
        </div>
    `
})

export class TestsComponent {

    items: string[] = [];

    constructor(
        private logService: LogService,
        private dataService: DataService) {

    }

    logM(message: string) {
        this.logService.WriteToLog(message);
    }

    store(message: string) {
        this.dataService.addData(message);
    }

    send(message: string) {
    }

    show() {
        this.items = this.dataService.getData();
    }

    deleteItem(message: string) {
        this.dataService.deleteMsg(message);
    }

    logarray() {
        this.logService.WriteToLog(this.items.toString());
    }
}

Now, everything is working good except when I try to delete an item. The log shows me that the item is still in the array, and therefore is still shown on the page. How can I remove the item after selecting it with the delete button??

Poul Kruijt
  • 58,329
  • 11
  • 115
  • 120
aghed aljlad
  • 1,585
  • 2
  • 12
  • 15

11 Answers11

256

You can't use delete to remove an item from an array. This is only used to remove a property from an object.

You should use splice to remove an element from an array:

deleteMsg(msg:string) {
    const index: number = this.data.indexOf(msg);
    if (index !== -1) {
        this.data.splice(index, 1);
    }        
}
Poul Kruijt
  • 58,329
  • 11
  • 115
  • 120
  • 21
    **Note:** If you don't check the return of `indexOf()` for `-1`, this will remove the last item from array when `msg` wasn't found! – Martin Schneider Feb 03 '17 at 15:08
153

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

adamdport
  • 8,779
  • 11
  • 58
  • 83
KaFu
  • 2,124
  • 1
  • 9
  • 11
38

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.

Community
  • 1
  • 1
martin
  • 76,615
  • 21
  • 156
  • 193
  • 5
    **Note:** If you don't check the return of `indexOf()` for `-1`, this will remove the last item from array when `msg` wasn't found! – Vinay Jeurkar Mar 06 '19 at 06:39
14
<tbody *ngFor="let emp of $emps;let i=index">

<button (click)="deleteEmployee(i)">Delete</button></td>

and

deleteEmployee(i)
{
  this.$emps.splice(i,1);
}
belwood
  • 2,444
  • 10
  • 32
  • 38
11

You can use like this:

removeDepartment(name: string): void {
    this.departments = this.departments.filter(item => item != name);
  }
Abdus Salam Azad
  • 3,109
  • 31
  • 23
9

This can be achieved as follows:

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

Felix Gerber
  • 1,555
  • 3
  • 23
  • 37
HamidKhan
  • 447
  • 6
  • 8
4

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);
}
Alessandro Ornano
  • 31,579
  • 11
  • 90
  • 115
  • Isn't this a little inefficient since you are doing 2 finds when you can just do 1? – rhavelka Jul 28 '20 at 15:15
  • @rhavelka Depend by the splice angular version: if your splice crash instead of getting null, this code should be safely to avoid unuseful splice.. – Alessandro Ornano Jul 28 '20 at 17:42
  • Right, I'm not saying your logic is flawed, just that it could be easily optimized. You're doing a `find`, then a `findIndex`, that's two searches when you could do one (like the accepted answer). – rhavelka Jul 28 '20 at 20:38
2

You can delete the data from array

this.data.splice(index, 1);
Jatin Devani
  • 199
  • 1
  • 9
2
//declaration 
list: Array<any> = new Array<any>(); 

//remove item from an array 
removeitem() 
{
const index = this.list.findIndex(user => user._id === 2); 
this.list.splice(index, 1); 
}
1

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)
mbadeveloper
  • 1,144
  • 8
  • 16
-3

That work for me

 this.array.pop(index);

 for example index = 3 

 this.array.pop(3);
Vishal Monga
  • 262
  • 2
  • 12