MarkeZ
MarkeZ

Reputation: 157

Delete selected items from array / list

I am using ng-multiselect-dropdown

 <ng-multiselect-dropdown [placeholder]="'Choose workers'" [data]="allWorkers"
                        [(ngModel)]="workers.selectedItems" [settings]="dropdownSettings"
                        (onSelect)="onItemSelect($event)" (onSelectAll)="onSelectAll($event)">
                      </ng-multiselect-dropdown>
                      {{selectedItems}}

I got my workers from api

allWorkers: string[] = [];

in my ngOnInit

this.workersService.getUsers().subscribe(
  (val: any[]) => {
    this.allWorkers = val.map(user => user.name + ' ' + user.city);
    console.log(this.allWorkers);
  }
)

all works fine but.. If I got

  onItemSelect(item: any) {

  }

I want to delete value from list if is selected

So if I have input:

and I select Name Surname2 I want to have only to choose

I tried something like this

onItemSelect(item: any) {
 const index = this.allWorkers.indexOf(item, 0);
    if (index > -1) {
      this.allWorkers.splice(index, 1);
    }
    }

But doesn't work.

Upvotes: 1

Views: 748

Answers (1)

lovis91
lovis91

Reputation: 2171

You should use the filter method :

this.allWorkers = this.allWorkers.filter(worker => worker !== item);

Upvotes: 6

Related Questions