【问题标题】:Trying to set the cursor position inside a textbox after updating the model object更新模型对象后尝试在文本框中设置光标位置
【发布时间】:2019-05-23 06:50:17
【问题描述】:

我想在更改模型对象后设置光标位置,但它实际上试图在更新文本框的值之前设置光标位置。

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);
    }

这样,因为它会在实际更新文本之前尝试设置光标位置,所以它只能focus()。但是,如果我没有将任何内容绑定到文本框并通过执行 this.myTextBox.setAttribute('value',str); 然后 focus() 并调用 setSelectionRange 来更新其文本,则它可以工作。我该怎么办?

【问题讨论】:

标签: angular textbox cursor-position ngmodel


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2017-09-17
    • 1970-01-01
    • 2016-11-28
    • 2015-04-08
    相关资源
    最近更新 更多