From 0e9c4f7f1eca123f86f1b0ac9b766d1e5e18ea72 Mon Sep 17 00:00:00 2001 From: Flok Date: Mon, 25 Nov 2024 08:46:02 +0100 Subject: [PATCH] fix(material/autocomplete): ensure selected option updates correctly on backspace Bug: Select an option from the autocomplete and close it. The input field is updated accordingly. Then click inside the input field and press backspace to update the input's value. The autocomplete panel opens, but the selected option is not updated yet. Pressing another backspace triggers the update. Problem and fix: When the `_handleInput` function is called, `panelOpen` is still `false`, causing the selected option to not update correctly. The `_openPanelInternal` function needs to be called to ensure the panel is open before processing the selected option logic. --- .../autocomplete/autocomplete-trigger.ts | 26 ++++++++++--------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/material/autocomplete/autocomplete-trigger.ts b/src/material/autocomplete/autocomplete-trigger.ts index 159c036ce973..7baf6f220a4d 100644 --- a/src/material/autocomplete/autocomplete-trigger.ts +++ b/src/material/autocomplete/autocomplete-trigger.ts @@ -529,18 +529,6 @@ export class MatAutocompleteTrigger if (!value) { this._clearPreviousSelectedOption(null, false); - } else if (this.panelOpen && !this.autocomplete.requireSelection) { - // Note that we don't reset this when `requireSelection` is enabled, - // because the option will be reset when the panel is closed. - const selectedOption = this.autocomplete.options?.find(option => option.selected); - - if (selectedOption) { - const display = this._getDisplayValue(selectedOption.value); - - if (value !== display) { - selectedOption.deselect(false); - } - } } if (this._canOpen() && this._document.activeElement === event.target) { @@ -553,6 +541,20 @@ export class MatAutocompleteTrigger this._valueOnLastKeydown = null; this._openPanelInternal(valueOnAttach); } + + if (value && this.panelOpen && !this.autocomplete.requireSelection) { + // Note that we don't reset this when `requireSelection` is enabled, + // because the option will be reset when the panel is closed. + const selectedOption = this.autocomplete.options?.find(option => option.selected); + + if (selectedOption) { + const display = this._getDisplayValue(selectedOption.value); + + if (value !== display) { + selectedOption.deselect(false); + } + } + } } }