Angular - 在不丢失光标位置的情况下更新输入字段

Angular - Updating an Input-Field without losing the cursor position

我真的很难解决这个问题,希望你 guys/girls 能帮助我。我在这个平台上查了很多网站和问题,但我没弄明白。

我想做的事情:

对于我的项目,我想创建自己的 ui-组件。其中之一是数字输入,它允许使用十进制数字,并使用千位和小数点分隔符很好地显示它们。当用户关注元素时,格式应该在每次更改时发生,而不是像其他解决方案那样,在元素模糊之后发生。

我的问题:

将值格式化为视觉上吸引人的字符串不是问题,因为我只使用十进制竖线。但是当我通过单向绑定更改输入字段的值时,用户光标移动到值的末尾。有没有办法停止这种行为并保持光标位置?

问题的简化版本

在输入字段中输入一些数字,它们将自动更改为 en-US 数字格式。然后将光标移动到左侧某处并输入一个新数字。输入字段将正确更新,但也会将光标移动到值的末尾。

https://stackblitz.com/edit/angular-input-field-example?file=src/app/app.component.ts

编辑: 在@Eliseo

的帮助下解决

用户@Eliseo 回答了这个问题并向 Whosebug 上的另一个问题发送了 link。使用那里提供的解决方案,我能够创建一个输入字段,它可以立即自动格式化我的输入,但也可以将光标保持在没有发生任何事情的位置。 魔法发生在指令 mask.directive.ts

https://stackblitz.com/edit/angular-input-field-solution?file=src/app/app.component.ts

这似乎可以解决问题。

  onInput(event): void {
    let position = event.target.selectionStart;
    this.value = +(<HTMLInputElement>event.target).value.split(',').join('');
    setTimeout(() => {
      event.target.selectionEnd = position;
    });
  }

你需要“玩”自己输入的属性selectionStart和selectionEnd,你可以在中看到一个例子(问题使用指令,它只是帮助你理解)

简化了这么多,如果自己传输入(也可以用viewChild问一下this.yourvariable.nativeElement)

<input #myinput type="text" class="form-control"
           [value]="value | number: '.0' : 'en-US'"
           (input)="onInput($event,myinput)">

有些喜欢

onInput(event: Event,inputhtml:any): void {
    //get the actual position of the cursor
    let pos=inputhtml.selectionStart;
    
    //get the characteres not digit before change:
    const nondigits=...

    //change the value
    this.value = +(<HTMLInputElement>event.target).value.split(',').join('');

    //recalcule the position, e.g.
     pos+=nondigits;

    //in a setTimeout (sometime this can be not neccesary)
    setTimeout(()=>{
       //use selectionStart and selectionEnd to position the cursor
       inputhtml.selectionStart=inputhtml.selectionEnd=pos

    })
  }