From 9ff35e96ad0f6731ea4efa628739e85e0919be2c Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Fri, 21 May 2021 07:51:54 +0200 Subject: [PATCH] fix(material/input): error for some input types on iOS `MatInput` has a `keyup` listener which calls `setSelectionRange` in order to work around an issue in iOS. The problem is that some input types don't allow the selection range to be updated and they throw an error if somebody tries to do it. These changes avoid the errors by detecting whether the input supports setting the selection range. Fixes #22726. --- src/material/input/input.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/material/input/input.ts b/src/material/input/input.ts index b3620b6c280d..01f7fab16ce7 100644 --- a/src/material/input/input.ts +++ b/src/material/input/input.ts @@ -269,8 +269,15 @@ export class MatInput extends _MatInputMixinBase implements MatFormFieldControl< if (_platform.IOS) { ngZone.runOutsideAngular(() => { _elementRef.nativeElement.addEventListener('keyup', (event: Event) => { - let el = event.target as HTMLInputElement; - if (!el.value && !el.selectionStart && !el.selectionEnd) { + const el = event.target as HTMLInputElement; + + // Note: We specifically check for 0, rather than `!el.selectionStart`, because the two + // indicate different things. If the value is 0, it means that the caret is at the start + // of the input, whereas a value of `null` means that the input doesn't support + // manipulating the selection range. Inputs that don't support setting the selection range + // will throw an error so we want to avoid calling `setSelectionRange` on them. See: + // https://html.spec.whatwg.org/multipage/input.html#do-not-apply + if (!el.value && el.selectionStart === 0 && el.selectionEnd === 0) { // Note: Just setting `0, 0` doesn't fix the issue. Setting // `1, 1` fixes it for the first time that you type text and // then hold delete. Toggling to `1, 1` and then back to