0

I have no idea how to run code snippet for angular app in stackoverflow,

I am using mat-autocomplete ,I have 128 char long name selected, the cursor appends at the end of the string selected instead on the beginning. Have anyone observed this when using mat-autocomplete?

enter image description here

Here is the example, In the stackblitz link link to code, I just appended letter 'v' for california, when I select 'california' I see the cursor at end instead I want the cursor at the beginning of the string.

In the code link under app > app.component.ts, check state variable, change name property to 128 char long string then from drop down down select option, you will see cursor appearing at end of string.

karansys
  • 2,449
  • 7
  • 40
  • 78

1 Answers1

1

With input and textarea there is no need to create custom Range as they provide their own API and in our case setSelectionRange() is what we need. But after using that, content of the input is still remains hidden, but looks like blur() and focus() does the trick.

optionSelected(input: HTMLInputElement) {
  input.blur();
  input.setSelectionRange(0, 0);
  input.focus();
}

<input ... #input>
<mat-autocomplete ... (optionSelected)="optionSelected(input)">

DEMO

Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81
  • Hi dev, that's perfect solution :), I had been searching across the internet for this solution, how did you find this? – karansys Jan 07 '20 at 18:36
  • 1
    Hi, experience and imagination :D Can't say its perfect/ Maybe in this simple case is perfect, because solution is very simple. You can inspect the Object in IDE to see what methods it provides and `setSelectionRange` is quite self explanatory. Then check it on MDN. And for `blur()` and `focus()` - thats the imagination :D Selection can be only one in the DOM, so when you focus, thats where the cursor is placed – Julius Dzidzevičius Jan 07 '20 at 19:42
  • Hi Dev, I added a new question https://stackoverflow.com/questions/59670262/how-to-display-entire-option-value-when-hovered-in-mat-autocomplete – karansys Jan 09 '20 at 18:51