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:
@ -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 {
|
||||
|
Reference in New Issue
Block a user