From fa2687f1a807f6c80c5d523d6add7b98e597c868 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 4 Mar 2024 19:11:16 +0100 Subject: [PATCH] fix(material/datepicker): always move caret to the end of the start input on backspace (#28669) When the user presses backspace on an empty end input of a range picker, we move focus to the start input and assume that the caret will be at the end. It appears that in some cases the browser decides to move it to the beginning instead so these changes reuse the logic from the left/right arrow handling to explicitly move it to the end on backspace as well. Fixes #28665. --- .../datepicker/date-range-input-parts.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/material/datepicker/date-range-input-parts.ts b/src/material/datepicker/date-range-input-parts.ts index 38fa45114796..fbb278676783 100644 --- a/src/material/datepicker/date-range-input-parts.ts +++ b/src/material/datepicker/date-range-input-parts.ts @@ -421,14 +421,24 @@ export class MatEndDate extends MatDateRangeInputPartBase { } } + private _moveCaretToEndOfStartInput() { + const startInput = this._rangeInput._startInput._elementRef.nativeElement; + const value = startInput.value; + + if (value.length > 0) { + startInput.setSelectionRange(value.length, value.length); + } + + startInput.focus(); + } + override _onKeydown(event: KeyboardEvent) { - const startInput = this._rangeInput._startInput; const element = this._elementRef.nativeElement; const isLtr = this._dir?.value !== 'rtl'; // If the user is pressing backspace on an empty end input, move focus back to the start. if (event.keyCode === BACKSPACE && !element.value) { - startInput.focus(); + this._moveCaretToEndOfStartInput(); } // If the user hits LEFT (LTR) when at the start of the input (and no // selection), move the cursor to the end of the start input. @@ -438,9 +448,7 @@ export class MatEndDate extends MatDateRangeInputPartBase { element.selectionEnd === 0 ) { event.preventDefault(); - const endPosition = startInput._elementRef.nativeElement.value.length; - startInput._elementRef.nativeElement.setSelectionRange(endPosition, endPosition); - startInput.focus(); + this._moveCaretToEndOfStartInput(); } else { super._onKeydown(event); }