Search code examples
angulartextboxcursor-positionngmodel

Trying to set the cursor position inside a textbox after updating the model object


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?


Solution

  • try this:

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