如何确定 Angular @HostListener 中按键或 keydown 事件中光标的位置(插入符号位置)

问题描述 投票:0回答:1

我需要确定光标的位置。这是我的代码:

    @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();
     }

};

有办法确定光标位置吗?我需要它,因为在我的输入类型数字中,用户可以通过在整个数字的开头甚至中间添加一个新数字来更改数字。由于我不知道光标的真实索引,因此我总是在末尾连接新的按键值。

333(用户光标)444

(用户光标)333444

在我当前的代码中,当用户输入 4 位小数并将光标置于开头输入新整数时,将触发 PreventDefault

angular typescript keypress keydown
1个回答
0
投票

最后我找到了适合我的解决方案:

 @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);

}
© www.soinside.com 2019 - 2024. All rights reserved.