3

Want to set cursor focus at end of the text for every <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);   
 }

enter image description here

but unable to set cursor at end of the text. Any one help me out in a angular way with out using Jquery.

Icarus
  • 1,627
  • 7
  • 18
  • 32
k11k2
  • 2,036
  • 2
  • 22
  • 36
  • 2
    Possible duplicate of [contenteditable, set caret at the end of the text (cross-browser)](https://stackoverflow.com/questions/4233265/contenteditable-set-caret-at-the-end-of-the-text-cross-browser) – Jeremy Thille Jan 17 '18 at 10:32

1 Answers1

3

Demo: https://stackblitz.com/edit/angular-svtdvv

Incorporated this answer in solution for browser compatibility: 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();
    }
  }
Michael Kang
  • 52,003
  • 16
  • 103
  • 135
  • I just added `(keydown)="keyDownEvent($event)"` to ``. In .ts for `rightarrow` placing caret end of next sibling column. but for `leftarrow` it placing caret at wrong position `event.key == "ArrowLeft" && event.srcElement.previousElementSibling != null) this.placeCaretAtEnd(event.srcElement.previousElementSibling);` what wrong going on here. – k11k2 Jan 30 '18 at 06:04