remove item from stored array in angular 2

前端 未结 11 1888
长发绾君心
长发绾君心 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:24

    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);
        }        
    }
    
    0 讨论(0)
  • 2020-12-23 03:25
    //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); 
    }
    
    0 讨论(0)
  • 2020-12-23 03:26

    That work for me

     this.array.pop(index);
    
     for example index = 3 
    
     this.array.pop(3);
    
    0 讨论(0)
  • 2020-12-23 03:27
    <tbody *ngFor="let emp of $emps;let i=index">
    
    <button (click)="deleteEmployee(i)">Delete</button></td>
    

    and

    deleteEmployee(i)
    {
      this.$emps.splice(i,1);
    }
    
    0 讨论(0)
  • 2020-12-23 03:27

    You can use like this:

    removeDepartment(name: string): void {
        this.departments = this.departments.filter(item => item != name);
      }
    
    0 讨论(0)
提交回复
热议问题