【问题标题】:Caret is moving backwards when a comma is added添加逗号时插入符号向后移动
【发布时间】:2018-03-30 08:50:19
【问题描述】:

我正在使用 Ionic(和 Angular)。我有一个指令,它在使用DecimalPipe 对其进行转换后更改输入的值。这些值只是数字。

问题是当一个逗号添加到数字时(例如:当用户将值从 100 更改为 1,000 时),光标会向后移动一位。 看起来它并不关心是否添加了逗号。

我的代码:

   let decimalPipe = new DecimalPipe(window.navigator.language);
   val = decimalPipe.transform(val, this.numberDecimal());


  this.model.valueAccessor.writeValue(val);
  this.renderer.setElementProperty(this.elementRef.nativeElement.querySelector('input'), 'value', val);

  this.model.viewToModelUpdate(val);

modelNgControl 类型,rendererRenderer 类型。

【问题讨论】:

    标签: angular ionic-framework caret cursor-position


    【解决方案1】:

    问题仅适用于 Android 设备。我没有找到解决方案,所以我编写了一个解决方法,在 0 毫秒超时后更改插入符号的位置。

    // before the change 
    let inputElem = this.elementRef.nativeElement.querySelector('input');
    let caretPos = inputElem.selectionStart;
    let numOfCommas = (value.match(/,/g) || []).length;
    ...
    
    //after the change
     let newNumOfCommas = (val.match(/,/g) || []).length;
     if (newNumOfCommas != numOfCommas)
     {
         setTimeout(() =>
         {
            let pos = newNumOfCommas > numOfCommas ? caretPos+1 : caretPos - 1;
            inputElem.setSelectionRange(pos, pos);
         }, 0);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      相关资源
      最近更新 更多