Input fields will have selectionStart property. By default it will be current cursor position. By using this property we can get current cursor position
Markup
Here on click on textarea and keyup on textarea will trigger getCaretPos function. This function passes Textarea element too.
<textarea rows="4" #myTextArea (click)="getCaretPos(myTextArea)" (keyup)="getCaretPos(myTextArea)" cols="40" >Sample Text Here, Place cursor here</textarea>
Script
Here we read selectionStart property as cursor position
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h2>Cursor Position : {{caretPos}}</h2> <div> <textarea rows="4" #myTextArea (click)="getCaretPos(myTextArea)" (keyup)="getCaretPos(myTextArea)" cols="40" >Sample Text Here, Place cursor here</textarea> </div> ` }) export class AppComponent { caretPos: number = 0; getCaretPos(oField) { if (oField.selectionStart || oField.selectionStart == '0') { this.caretPos = oField.selectionStart; } } }
Nice work!!
ReplyDeleteGreat. How do I insert text at the cursor position?
ReplyDeleteuse string functions like substr to paste in the new data and then move the cursor too
DeleteSuperb!
ReplyDeleteThank you a lot!
ReplyDelete