Skip to content

Commit

Permalink
fix(select): correctly handle reset value when multiple is on (#2815)
Browse files Browse the repository at this point in the history
  • Loading branch information
chirichok98 authored Aug 27, 2021
1 parent 7753027 commit 37a0bc2
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions src/framework/theme/components/select/select.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1024,7 +1024,7 @@ export class NbSelectComponent implements OnChanges, AfterViewInit, AfterContent

protected setActiveOption() {
if (this.selectionModel.length) {
this.keyManager.setActiveItem(this.selectionModel[ 0 ]);
this.keyManager.setActiveItem(this.selectionModel[0]);
} else {
this.keyManager.setFirstItemActive();
}
Expand Down Expand Up @@ -1155,23 +1155,29 @@ export class NbSelectComponent implements OnChanges, AfterViewInit, AfterContent
* Set selected value in model.
* */
protected setSelection(value) {
const isArray: boolean = Array.isArray(value);
const isResetValue = value == null;
let safeValue = value;

if (this.multiple && !isArray) {
throw new Error('Can\'t assign single value if select is marked as multiple');
if (this.multiple) {
safeValue = value ?? [];
}

const isArray: boolean = Array.isArray(safeValue);

if (this.multiple && !isArray && !isResetValue) {
throw new Error('Can\'t assign single value if select is marked as multiple');
}
if (!this.multiple && isArray) {
throw new Error('Can\'t assign array if select is not marked as multiple');
}

const previouslySelectedOptions = this.selectionModel;
this.selectionModel = [];

if (isArray) {
value.forEach(option => this.selectValue(option));
if (this.multiple) {
safeValue.forEach(option => this.selectValue(option));
} else {
this.selectValue(value);
this.selectValue(safeValue);
}

// find options which were selected before and trigger deselect
Expand All @@ -1186,6 +1192,10 @@ export class NbSelectComponent implements OnChanges, AfterViewInit, AfterContent
* Selects value.
* */
protected selectValue(value) {
if (value == null) {
return;
}

const corresponding = this.options.find((option: NbOptionComponent) => this._compareWith(option.value, value));

if (corresponding) {
Expand Down

0 comments on commit 37a0bc2

Please sign in to comment.