Skip to content

Commit fa2687f

Browse files
authored
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.
1 parent b169320 commit fa2687f

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/material/datepicker/date-range-input-parts.ts

+13-5
Original file line numberDiff line numberDiff line change
@@ -421,14 +421,24 @@ export class MatEndDate<D> extends MatDateRangeInputPartBase<D> {
421421
}
422422
}
423423

424+
private _moveCaretToEndOfStartInput() {
425+
const startInput = this._rangeInput._startInput._elementRef.nativeElement;
426+
const value = startInput.value;
427+
428+
if (value.length > 0) {
429+
startInput.setSelectionRange(value.length, value.length);
430+
}
431+
432+
startInput.focus();
433+
}
434+
424435
override _onKeydown(event: KeyboardEvent) {
425-
const startInput = this._rangeInput._startInput;
426436
const element = this._elementRef.nativeElement;
427437
const isLtr = this._dir?.value !== 'rtl';
428438

429439
// If the user is pressing backspace on an empty end input, move focus back to the start.
430440
if (event.keyCode === BACKSPACE && !element.value) {
431-
startInput.focus();
441+
this._moveCaretToEndOfStartInput();
432442
}
433443
// If the user hits LEFT (LTR) when at the start of the input (and no
434444
// selection), move the cursor to the end of the start input.
@@ -438,9 +448,7 @@ export class MatEndDate<D> extends MatDateRangeInputPartBase<D> {
438448
element.selectionEnd === 0
439449
) {
440450
event.preventDefault();
441-
const endPosition = startInput._elementRef.nativeElement.value.length;
442-
startInput._elementRef.nativeElement.setSelectionRange(endPosition, endPosition);
443-
startInput.focus();
451+
this._moveCaretToEndOfStartInput();
444452
} else {
445453
super._onKeydown(event);
446454
}

0 commit comments

Comments
 (0)