New to Kendo UI for AngularStart a free 30-day trial

Positioning Cursor at the End of Text in the TextBox

Environment

ProductProgress® 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 setSelectionRange in 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:

  1. Use the @ViewChild decorator to get a reference to the TextBox component:

    html
    <kendo-textbox #textbox> </kendo-textbox>
    typescript
    import { ViewChild } from '@angular/core';
    import { TextBoxComponent } from '@progress/kendo-angular-inputs';
    
    export class AppComponent {
      @ViewChild('textbox') textBox!: TextBoxComponent;
    }
  2. In the component class, create a method that sets the caret position to the end of the text when the TextBox receives focus:

    typescript
    public onInputFocus(): void {
      // Use requestAnimationFrame to ensure the DOM is updated before setting the caret.
      requestAnimationFrame(() => this.setCaretToEnd());
    }
  3. In the setCaretToEnd method, 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:

    typescript
    private 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;
      }
    }
  4. Bind the created onInputFocus method to the inputFocus event 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:

Change Theme
Theme
Loading ...

See Also

In this article
EnvironmentDescriptionSolutionSee Also
Not finding the help you need?
Contact Support