Reputation: 3747
I want the textfield to automatically point to the end of the text once the user clicks on it. This was working before with setSelection, but for some reason it stopped working. Now the cursor point to wherever the user clicks.
HMTL:
<TextField text="the cursor should point at the end when clicked" (focus)="onFocus($event.object)"> </TextField>
TS:
public onFocus(textfield): void {
textfield.android.setSelection(textfield.text.length)
}
If I wrap it inside of a timeout it works but it flashes before the cursor moves which I'm not very happy with. I also made a playground example
Thanks in advance for your help!
Upvotes: 5
Views: 1792
Reputation: 3747
Ok, I found a solution for this. It's a little bit of a hack, but it does the trick for me. The main difference with the setTimeout is that this doesn't 'flash' before moving the cursor.
Ok, so my solution: I use a conditional css class inside of the textfield depending whether or not the textfield is focused. This causes the life cycle hooks to run one more time once the textfield is ready (at least that's what I think is happening).
Here is my code now: HTML:
<TextField [class.default-padding]="isFocused" text="the cursor should point at the end when clicked" (focus)="onFocus($event.object)" (blur)="onBlur()"> </TextField>
CSS:
.default-padding {
/* This is just a dummy value. You can use any other padding or margin or
anything that will cause the hooks to re-render*/
padding-right: 0;
}
TS:
private isFocused = false
public onFocus(textfield): void {
this.isFocused = true
textfield.android.setSelection(textfield.text.length)
}
public onBlur(): void {
this.isFocused = false
}
Here is my updated playground example
Upvotes: 2
Reputation: 21908
It seems to work as expected. Remember, on Android focus is when the cursor is placed on TextField. If you press back button to hide keyboard and click anywhere on TextField to show keyboard again, that will not trigger focus event again.
It points cursor to end of TextField when I tap on TextField, it will not if I tap on same TextField again. But if I tap on the second TextField then it should work as expected there as the focus now shifts from first TextField to second.
If you still have issues, please share your device OS version and possibly a GIF that shows the issue.
Upvotes: 0