How to determine the position of the cursor (caret position) in keypress or keydown event in Angular @HostListener

58 views Asked by At

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

1

There are 1 answers

0
Jmainol On

At last I found this solution that works for me:

 @HostListener('keydown', ['$event']) disableKeys = (e: KeyboardEvent): any => {
  let currentValue: string = (<HTMLInputElement>e.target).value || '';
  let position = (<HTMLInputElement>e.composedPath().shift()).selectionStart;
  let nextValue = e.key as any; 

  // only allow to enter interger numbers or decimal up to 4 positions
  const regex = /^\d+(\.\d{0,4})?$/

 let currentValueArray =  [...currentValue];

 if (currentValue) {      
  let nextValueArray = [
  ...currentValueArray.slice(0, position!),
  nextValue,
  ...currentValueArray.slice(position!),
];

  nextValue = nextValueArray.join('')
 }

 console.log('nextValue: ', nextValue);

}

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