7
<div id="editable" contenteditable="true" class="search-input" [textContent]="query" (input)="query=$event.target.textContent" (keyup)="searchClient($event)" (focus)="open()"></div>

This is my HTML code and put the DIV that supports content editable. When I press any key then the searchClient($event) method is triggered and set some value. I need to set the caret(cursor) end of the value and focus it.

I tried out few example but I couldn't figure it out the solution for Angular 4.

Note: I tried out How to set caret(cursor) position in contenteditable element (div)? got this error SearchComponent.html:6 ERROR TypeError: Failed to execute 'setStart' on 'Range': parameter 1 is not of type 'Node'.

Damith Ganegoda
  • 4,100
  • 6
  • 37
  • 46
  • 1
    Possible duplicate of [How to set caret(cursor) position in contenteditable element (div)?](https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div) – Christian Benseler Nov 22 '17 at 16:04
  • Thanks, I tried out that example too before I posted it. Got this error. SearchComponent.html:6 ERROR TypeError: Failed to execute 'setStart' on 'Range': parameter 1 is not of type 'Node'. – Damith Ganegoda Nov 22 '17 at 16:08

2 Answers2

0

You can handle this if you use the Renderer2 API.

1º) Create a variable of the tag you want to focus on and create an event to call a function to change the cursor location. Like:

<div class="example" #tagDiv>
     I want to focus in here.
</div>
<button (onclick)="changeCursorLocation()"> Click here </button>

2º) In the component create a ViewChild() and the function:

  @ViewChild("tagDiv") tagDivField: ElementRef;
  changeCursorLocation(){
      const element = this.renderer.selectRootElement('#tagDiv', true);
      element.focus();
  }

Renderer2: (https://angular.io/api/core/Renderer2)

I did not run this specific peace of code, but i have done something like this in the past and it worked very well. So, I hope it can of any help.

Obs: Remenber to import Renderer2 and ElementRef;

Robson Sampaio
  • 307
  • 1
  • 5
-2

You can change it with this...

<div id="editable" contenteditable="true" class="search-input" [textContent]="query" (input)="Revisedquery=$event.target.textContent" (keyup)="searchClient($event)" (focus)="open()"></div>

Also find this usefull link for deeply study the matter.
https://github.com/angular/angular/issues/9796