Inamur Rahman
Inamur Rahman

Reputation: 3291

ng-select remove the element in programmatic way in Angular 6

I am trying to remove the selected element from the ng-select using the program. As we can delete it using click cross button but we want to delete programmatic way in Angular 6. Please help me to find a perfect solution.

enter image description here

Upvotes: 2

Views: 7353

Answers (2)

Oussail
Oussail

Reputation: 2288

You want only this line :

this.selectedCityIds = this.selectedCityIds.filter(s => s != id);

Which is you can use it in your function in this way;

deleteSingle (id: string) {
  this.selectedCityIds = this.selectedCityIds.filter(s => s != id);
}

Upvotes: 4

igg
igg

Reputation: 2250

Your ng-select is 2-way bound with selectedCityIds, this is what the [(ngModel)] notation does. Meaning, changing one (either the GUI ng-select or the class property selectedCityIds) changes the other. Here is a proposed solution:

I created a text input which lets users type the name of a city.

<label>Type name of city to delete</label>
<input type="text" [(ngModel)]="cityToDelete" style="margin-left: 10px" />

Then, your deleteSingle method is completed like this:

// This is the property bound to the text input
cityToDelete: string = "";
deleteSingle () {
  // This will be the city to delete
  const city = this.cities2.find(c => c.name === this.cityToDelete);
  // If city with this name is found in list, then it's removed
  if(city != null) {
    console.log(city);
    this.selectedCityIds = this.selectedCityIds.filter(id => id !== city.id);
  }
}

Stackblitz here.

Try it out:

  1. Add "Vilnius" and "Kaunas" to your ng-select.
  2. Type one of the above names in the text input.
  3. Click "Delete City By name"

You will see the city name you typed will be removed from the GUI. The code searched your ng-select data source, which is cities2 in your example. If a city with the name the user types is not found in cities2, no action is taken.

Upvotes: 1

Related Questions