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

1

6

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?

Kincardine answered 23/5, 2019 at 6:50 Comment(2)
This could help: #40932345Prevost
you can use ngModelChange and ngModelOption on blur to do the focus part read more in article : #44841235Dessertspoon
T
7

try this:

updateText(str:String){
    this.myString+=str;
    setTimeout(()=>{
        this.myTextBox.focus();
        this.myTextBox.setSelectionRange(2,2);
    },0);
}
Typify answered 23/5, 2019 at 7:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.