Search code examples
angularangular-ngselect

Removing item from *ngFor is not reflecting in ng-select dropdown


I am using ng-select library from https://www.npmjs.com/package/@ng-select/ng-select.

Initially I have created dropdown with some values.

    <ng-select
      [items]="cities"
      bindLabel="name"
      placeholder="Select city"
      [(ngModel)]="selectedCity">
    </ng-select>
cities = [
    { id: 1, name: 'Vilnius' },
    { id: 2, name: 'Kaunas' },
    { id: 3, name: 'Pavilnys' },
    { id: 4, name: 'Pabradė' },
    { id: 5, name: 'Klaipėda' }
  ];

Now, I want to remove some items from the above cities list at runtime.

For that, I am calling splice on that list to remove the items.

removeItem() {
    this.cities.splice(0, 1);
  }

The value is remove from the list but the same thing is not reflected at the UI part.

I have also tried change detection strategy but that didn't work.

I have created the example at https://stackblitz.com/edit/ng-select-21cubn.


Solution

  • As mentioned in the doc, you can do:

    this.cities.splice(0, 1);
    this.cities = [...this.cities];
    

    Or:

    this.cities = this.cities.slice(1);
    

    Then the component will detect the change and update.

    Stackblitz