5

I want to set the cursor position after changing the model object but it actually tries to set the cursor position before updating the value of the textbox.

HTML:

    <input type="text" name="test" id="test" [(ngModel)]="myString">
    <button type="button" (click)="updateText('testStr')">

TS:

    myTextBox: HTMLInputElement;

    ngOnInit() {
    this.myTextBox = document.getElementById('test');
    }

    updateText(str:String){
    this.myString+=str;
    this.myTextBox.focus();
    this.myTextBox.setSelectionRange(2,2);
    }

This way, because it tries to set the cursor position before actually updating the text, it can only focus(). But, if I don't bind anything to the textbox and update its text by doing this.myTextBox.setAttribute('value',str); and then focus() and call setSelectionRange it works. What should I do?

Lahiru Mirihagoda
  • 1,113
  • 1
  • 16
  • 30
oksuzlerOmer
  • 125
  • 1
  • 2
  • 11
  • 1
    This could help: https://stackoverflow.com/questions/40931845/angular2-keyup-event-update-ngmodel-cursor-position-jumps-to-end – Jojofoulk May 23 '19 at 07:02
  • you can use ngModelChange and ngModelOption on blur to do the focus part read more in article : https://stackoverflow.com/questions/44840735/change-vs-ngmodelchange-in-angular – Joel Joseph May 23 '19 at 07:14

1 Answers1

5

try this:

updateText(str:String){
    this.myString+=str;
    setTimeout(()=>{
        this.myTextBox.focus();
        this.myTextBox.setSelectionRange(2,2);
    },0);
}
liqSTAR
  • 1,225
  • 1
  • 12
  • 22