I'm using Ionic (and Angular). I have a directive which changes the value of an input after transforming it using DecimalPipe. The values are numeric only.
The problem is that when a comma is added to the number (for example: when the user changes the value from 100 to 1,000) the cursor is moving backward one place. It looks like it doesn't care that a comma was added.
My code:
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);
The model
is of type NgControl and the renderer
is of type Renderer.
The problem was for Android devices only. I didn't find a solution so I wrote a workaround that changes the caret's position after a timeout of 0 milliseconds.
// 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);
}