diff --git a/src/ng-select/items-list.ts b/src/ng-select/items-list.ts index 401ba0378..584a4873e 100644 --- a/src/ng-select/items-list.ts +++ b/src/ng-select/items-list.ts @@ -238,7 +238,7 @@ export class ItemsList { const multiple = this._ngSelect.multiple; for (const selected of this.selectedItems) { const value = this._ngSelect.bindValue ? this.resolveNested(selected.value, this._ngSelect.bindValue) : selected.value; - const item = this.findItem(value); + const item = isDefined(value) ? this.findItem(value) : null; this._selectionModel.unselect(selected, multiple); this._selectionModel.select(item || selected, multiple, this._ngSelect.selectableGroupAsModel); } diff --git a/src/ng-select/ng-select.component.spec.ts b/src/ng-select/ng-select.component.spec.ts index 3bd758101..3d294e64a 100644 --- a/src/ng-select/ng-select.component.spec.ts +++ b/src/ng-select/ng-select.component.spec.ts @@ -359,6 +359,30 @@ describe('NgSelectComponent', function () { expect(select.itemsList.filteredItems[0].selected).toBeTruthy(); })); + it('should keep selected item while setting new items and bindValue is incorrect', fakeAsync(() => { + const fixture = createTestingModule( + NgSelectTestCmp, + ` + `); + + tickAndDetectChanges(fixture); // triggers write value + + select = fixture.componentInstance.select; + select.select(select.itemsList.items[1]); + tickAndDetectChanges(fixture); + + fixture.componentInstance.cities = [...fixture.componentInstance.cities]; + tickAndDetectChanges(fixture); + + expect(select.selectedItems[0]).toEqual(jasmine.objectContaining({ + value: { id: 2, name: 'Kaunas' } + })); + })); + it('should clear previous single select value when setting new model', fakeAsync(() => { const fixture = createTestingModule( NgSelectTestCmp,