HelpBot Assistant

How can I help you?

Set cursor position on focus in Angular MaskedTextBox component

26 Feb 20263 minutes to read

By default, the entire mask is selected when the MaskedTextBox receives focus. Use the focus event to customize the cursor position by using any of the following methods:

  • Set cursor position at the start of the MaskedTextBox
  • Set cursor position at the end of the MaskedTextBox
  • Set cursor position at a specific location within the MaskedTextBox

When the MaskedTextBox contains only mask characters, selectionStart and selectionEnd are set to 0 instead of the input value’s length. This is the default behavior of the HTML 5 input element and occurs because the input technically contains no data.

The following example demonstrates how to set the cursor position in the MaskedTextBox.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { MaskedTextBoxModule } from '@syncfusion/ej2-angular-inputs'



import { Component } from '@angular/core';

@Component({
imports: [
        MaskedTextBoxModule
    ],


standalone: true,
    selector: 'app-root',
    // sets mask format to the MaskedTextBox
    template: `
            <div class="col-sm-6">
                <br/><ejs-maskedtextbox #mask="" id="mask1" mask='00000-00000' value='93828-32132' name="mask_value1" placeholder= 'Default cursor position' floatLabelType= 'Always'></ejs-maskedtextbox><br/>
                <ejs-maskedtextbox #mask="" id="mask2" mask='00000-00000' value='83929-4342' name="mask_value2" placeholder= 'Cursor positioned at start' floatLabelType= 'Always' (focus)= "onStartfocus($event)"></ejs-maskedtextbox><br/>
                <ejs-maskedtextbox #mask="" id="mask3" mask='00000-00000' value='83929-3213' name="mask_value3" placeholder= 'Cursor positioned at end' floatLabelType= 'Always' (focus)= "onEndfocus($event)"></ejs-maskedtextbox><br/>
                <ejs-maskedtextbox #mask="" id="mask4" mask='+1 000-000-0000' value='234-432-432' name="mask_value4" placeholder= 'Cursor at specified position' floatLabelType= 'Always' (focus)= "onSpecificfocus($event)"></ejs-maskedtextbox>
            </div>
    `
})

export class AppComponent {
    public onStartfocus(args: any): void {
        //sets cursor position at start of MaskedTextBox
        args.selectionEnd= args.selectionStart = 0;
        }
        public onEndfocus(args: any): void {
        //sets cursor position at end of MaskedTextBox
        args.selectionStart=args.selectionEnd = args.maskedValue.length;
        }
        public onSpecificfocus(args: any): void {
        //sets cursor at specified position
        args.selectionStart = 3;
        args.selectionEnd = 3;
    }
}
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));