I'm having an issue with my HTML input field and the typescript component that is using ngModelChange. I want to be able to edit the input value wherever I need to.
For example:
- original input is auto-filled with is "00:00:00". I want to edit it to "01:20:00".
- with my keyboard I position the cursor (^) where I need it to 0^0:00:00
- I type in 1, the result is "01:00:00^"
- If I want to add the 2, I need to move the cursor again, and that for me is not desirable.
I know this is a known issue that could be fixed with re-setting the cursor using setSelectionRange, however that has not worked since even if I used the setSelectionRange(selectionStart, selectionEnd) with the correct value of the cursor, the ngModelChange, would put the cursor back to the end.
I also have a Regex that applies the colon after each two digits.
Although this is my code, I also provide a stackblitz where you can play with it: https://stackblitz.com/edit/angular-ivy-adynjf?file=src/app/app.compone
This is my input field:
<input
id="value"
type="text"
[ngModel]="changedValue"
(ngModelChange)="formatAndChange($event)"
/>
and part of my component:
export class AppComponent {
public changedValue: String = "00:00:00";
public formatAndChange(inputValue: string) {
this.changedValue = inputValue;
if (inputValue.length > 8) {
inputValue = inputValue.substr(0, 8);
}
let unformat = inputValue.replace(/\D/g, "");
if (unformat.length > 0) {
inputValue = unformat.match(new RegExp(".{1,2}", "g")).join(":");
}
this.changedValue = new String(inputValue);
}
}
Basically my question is, how is this structure supposed to be used if we want it all: the value changes and is formatted while the user is typing (we add the colon so the format is correct), and the cursor stays in place (ngModelChange does not change the cursor placement or at least I can make it return to where it was)
Appreciate it. Thanks!!