fix (forms): clear selected options when model is not an array (#12519)

When an invalid model value (eg empty string) was preset ngModel on
select[multiple] would throw an error, which is inconsistent with how it
works on other user input elements. Setting the model value to null or
undefined would also have no effect on what was already selected in the
UI. Fix this by clearing selected options when model set to null,
undefined or a type other than Array.

Closes #11926
This commit is contained in:
gary-b
2016-12-14 16:34:19 +00:00
committed by Victor Berchet
parent d40bbf4d5c
commit 547bfa92ef
2 changed files with 83 additions and 7 deletions

View File

@ -66,11 +66,15 @@ export class SelectMultipleControlValueAccessor implements ControlValueAccessor
writeValue(value: any): void {
this.value = value;
if (value == null) return;
const values: Array<any> = <Array<any>>value;
// convert values to ids
const ids = values.map((v) => this._getOptionId(v));
this._optionMap.forEach((opt, o) => { opt._setSelected(ids.indexOf(o.toString()) > -1); });
let optionSelectedStateSetter: (opt: NgSelectMultipleOption, o: any) => void;
if (Array.isArray(value)) {
// convert values to ids
const ids = value.map((v) => this._getOptionId(v));
optionSelectedStateSetter = (opt, o) => { opt._setSelected(ids.indexOf(o.toString()) > -1); };
} else {
optionSelectedStateSetter = (opt, o) => { opt._setSelected(false); };
}
this._optionMap.forEach(optionSelectedStateSetter);
}
registerOnChange(fn: (value: any) => any): void {