【发布时间】: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 来更新其文本,则它可以工作。我该怎么办?
【问题讨论】:
-
你可以使用 ngModelChange 和 ngModelOption on blur 来做焦点部分阅读更多文章:stackoverflow.com/questions/44840735/…
标签: angular textbox cursor-position ngmodel