@HostListener ('KeyDown', ['$event','$event. KeyCode']) OnKeyDown ($Event: KeyboardEvent, KeyCode) { if(KeyCode!==TAB) { $Event. Preventdefault (); } //Get value for the key Constval =String. fromCharCode (KeyCode); //Get position ConstCursorpos = This. Input. SelectionStart; Switch(keycode) { CaseLeft_arrow: This. Handleleftarrow (Cursorpos); return; CaseRight_arrow: This. Handlerightarrow (Cursorpos); return; } overwritecharatposition ( This. Input, Val, cursorpos); This. Handlerightarrow (Cursorpos); } handlerightarrow (Cursorpos) {ConstValuebeforecursor = This. Input.value.slice (Cursorpos +1); ConstNextpos = FindIndex (Valuebeforecursor, (Char) =!includes (Special_characters,Char)); if(Nextpos >-1) { ConstNewnextpos = Cursorpos + Nextpos +1; This. Input. Setselectionrange (Newnextpos, Newnextpos); }} handleleftarrow (Cursorpos) {ConstValueaftercursor = This. Input.value.slice (0, Cursorpos); ConstPreviouspos = FindLastIndex (Valueaftercursor, (Char) =!includes (Special_characters,Char)); if(Previouspos >-1) { This. Input. Setselectionrange (Previouspos, Previouspos); } }
We can use the ' Setselectionrange (start, end) ' To set the cursor postion, in which start postion = end position.
[Angular HTML] Implementing the Input Mask Cursor Navigation functionality--Setselectionrange