How to set cursor position in a data-binding textarea?


I wan to set cursor position in a textarea,I found that if I wanna use the fucntion setSelectionRange(),I have to use NativeElement. So my code is like this:


<ion-label floating>What are you doing</ion-label> 
     <ion-textarea  #post rows='12' [(ngModel)]="data.message" (ngModelChange)='msgCount($event)'></ion-textarea>


export class PostPage implements OnInit{
        @ViewChild('post') postEl;
        constructor(public params:NavParams,public elRef: ElementRef){{
        let msg=this.params.get('msg');
          let el=this.elRef.nativeElement.querySelector('textarea');
    setCaretPosition(elem, caretPos) {
       var range;
       if (elem.createTextRange) {
           range = elem.createTextRange();
           range.move('character', caretPos);
       } else {
          elem.setSelectionRange(caretPos, caretPos);


But I can set focus ,but fail to set the the cursor position.
Then I changed the ion-textarea to textarea,but still not worked.
I googled and found a demo Set Cursor Position In Text Area Using Angular 2.
I found that his textarea does not hava any data-binding,and textarea’s value is not empty.This is biggest difference between his and mine.
So I add a line of code:

but still not worked out.

Sorry for my poor English.

Thanks in advance.


now something that does not help you in this case but a little advice:

If you need to use elementref and selecting an element with native javascript --> there is something wrong.
You should not do this in a component.


  1. Create a “TextSelectionDirective”
  2. there you get with ElementRef the textarea itself
  3. Pass the value of the textarea with ngcontent or @Input


Thanks for your advice!