I need to determinate de position of the cursor. Here my code:
@HostListener('keypress', ['$event']) disableKeys = (e: KeyboardEvent): any => {
const currentValue: string = (<HTMLInputElement>e.target).value || '';
const nextValue = `${currentValue}${e.key}`;
// only allow to enter interger numbers or decimal up to 4 positions
const regex = /^\d+(\.\d{0,4})?$/
if (nextValue && !this._regex.test(String(nextValue))) {
e.preventDefault();
}
};
Are there anyway to determinate cursor position? I need it because in my input type number user can change the number by adding a new one at the beggining of the whole number or even in the middle. As I dont know the real index of the cursor, I´m always concating the new keypress value at the end.
333(user cursor)444
(user cursor)333444
With my current code, when user enters 4 decimals and positions the cursor at the beginning to enter a new integer, the preventDefault is fired
At last I found this solution that works for me:
The key is using
e.composedPath().shift()).selectionStart. The index of the cursor (caret position) will be display after press a key (fire event keydown). Just clicking to change the caret position outputs undefined