I'm currently facing an issue with my HTML input field combined with a typescript component utilizing ngModelChange. I am aiming to have the flexibility to edit the input value wherever necessary.
Let's consider this scenario:
- The original input is pre-filled with "00:00:00". I wish to modify it to "01:20:00".
- Using my keyboard, I move the cursor (^) to where I want it: 0^ 0:00:00
- I type '1', and the output shows "01:00:00^"
- If I try adding '2', I must relocate the cursor again, which is not ideal for me.
I am aware that there is a known workaround involving resetting the cursor position using setSelectionRange. However, my attempts at using setSelectionRange(selectionStart, selectionEnd) with the correct cursor location have been unsuccessful as ngModelChange reverts the cursor back to the end.
Additionally, I have a Regex pattern in place that automatically inserts a colon after every two digits.
While I have shared my code snippet, you can also experiment with it on StackBlitz: https://stackblitz.com/edit/angular-ivy-adynjf?file=src/app/app.compone
This is the structure of my input field:
<input
id="value"
type="text"
[ngModel]="changedValue"
(ngModelChange)="formatAndChange($event)"
/>
Here is a snippet from 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);
}
}
In essence, my query revolves around the optimal usage of this structure. How can we ensure that both the value changes are formatted while the user inputs data (including the insertion of colons for correct formatting), and maintain the fixed cursor position without being affected by ngModelChange?
Your insights are greatly appreciated. Thank you!