想要将光标焦点设置在每个<td>
<table #sampleTable>
<th>name</th>
<th>number</th>
<tr>
<td #name contenteditable="true">
jack
</td>
<td #number contenteditable="true">
5487
</td>
</tr>
</table>
component.ts
@ViewChild('name') colName;
...
ngAfterViewInit(){
setTimeout(() => {
this.colName.nativeElement.focus() //setting focus at name column
}, 1000);
}
但无法将光标设置在文本的末尾。任何人都可以使用Jquery以角度的方式帮助我。
答案 0 :(得分:3)
演示:https://stackblitz.com/edit/angular-svtdvv
在解决方案中将此答案纳入浏览器兼容性: contenteditable, set caret at the end of the text (cross-browser)
@ViewChild('name') colName;
ngAfterViewInit() {
this.placeCaretAtEnd(this.colName.nativeElement);
this.colName.nativeElement.focus();
}
placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
else if (typeof (<any>document.body).createTextRange != "undefined") {
var textRange = (<any>document.body).createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}