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); }