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:
post.html
<ion-label floating>What are you doing</ion-label>
<ion-textarea #post rows='12' [(ngModel)]="data.message" (ngModelChange)='msgCount($event)'></ion-textarea>
</ion-label>
post.ts
export class PostPage implements OnInit{
@ViewChild('post') postEl;
constructor(public params:NavParams,public elRef: ElementRef){
this.data={
message:''
};
}
ngOnInit(){
let msg=this.params.get('msg');
if(msg){
let el=this.elRef.nativeElement.querySelector('textarea');
this.data['message']=msg;
this.setCaretPosition(el,0);
}
}
setCaretPosition(elem, caretPos) {
var range;
console.log(elem);
if (elem.createTextRange) {
range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
elem.focus();
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:
this.postEl.nativeElement.value=msg;
but still not worked out.
Sorry for my poor English.
Thanks in advance.