Positioning Cursor at the End of Text in the TextBox
Environment
| Product | Progress® Kendo UI® for Angular TextBox |
Description
I want to set the cursor to the end of the text in the Kendo UI for Angular TextBox component. Additionally, I need the end part of the text to be visible in case the text exceeds the width of the TextBox.
This Knowledge Base article also answers the following questions:
- How to set the caret at the end in Kendo UI for Angular TextBox?
- How to ensure the last part of the text is visible in Kendo UI for Angular TextBox?
- How to work with
setSelectionRangein Kendo UI for Angular TextBox?
Solution
To position the cursor at the end of the text and ensure that the last part of the text is visible, use the setSelectionRange method of the TextBox's inner input element. Then, adjust the scrollLeft property of the input to scroll to the end of the text.
Follow the steps below to achieve the full implementation:
-
Use the
@ViewChilddecorator to get a reference to the TextBox component:html<kendo-textbox #textbox> </kendo-textbox>typescriptimport { ViewChild } from '@angular/core'; import { TextBoxComponent } from '@progress/kendo-angular-inputs'; export class AppComponent { @ViewChild('textbox') textBox!: TextBoxComponent; } -
In the component class, create a method that sets the caret position to the end of the text when the TextBox receives focus:
typescriptpublic onInputFocus(): void { // Use requestAnimationFrame to ensure the DOM is updated before setting the caret. requestAnimationFrame(() => this.setCaretToEnd()); } -
In the
setCaretToEndmethod, set the selection range of the input to the length of its value and scroll the input element to display the end of the text:typescriptprivate setCaretToEnd(): void { if (this.textBox && this.textBox.input) { const inputElement = this.textBox.input.nativeElement; const textLength = inputElement.value.length; // Set selection range to the end inputElement.setSelectionRange(textLength, textLength); // Scroll to show the end of the text inputElement.scrollLeft = inputElement.scrollWidth; } } -
Bind the created
onInputFocusmethod to theinputFocusevent of the TextBox:html<kendo-textbox #textbox [style.width.px]="200" [(ngModel)]="textValue" (inputFocus)="onInputFocus()"> </kendo-textbox>
The following example demonstrates how to set the cursor at the end of the text in the Kendo UI for Angular TextBox component: