-1

I have a custom Angular pipe that transforms entered text into a series of dots after the user leaves the input field. When the user re-enters the input field, the text should transform back into the entered data, with the carat appearing at the end of the field, regardless of user placement.

This works fine in all browsers, except IE11, where the carat momentarily appears at the end of the input field, and then jumps to the start of the input field. This behavior can be seen at this Stackblitz sandbox.

How can I transform the data with an Angular pipe while keeping the carat at the end of the input field across all browsers?

Edit: I've refactored my code and utilized setSelectionRange() as suggested by Zhi Li's answer.

Griffin
  • 710
  • 2
  • 15
  • 29

1 Answers1

1

Try to use the JQuery function to set cursor at the end of the input field. Please refer to the following steps:

  1. using the following comment to install JQuery:

    npm install jquery --save

  2. In the angular.json file, find the scripts node, then add JQuery script:

    "scripts": ["node_modules/jquery/dist/jquery.min.js"]

  3. using the following code to set cursor:

Code in the component.ts:

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery'
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit  {
  showSsnMask = true;
  ssnValue= 123456789;

  public ngOnInit(){

    $(document).ready(function() {  
      $("#txtsearch").focus(function(){        
        var input = $(this);
        var len = input.val().length;
        input[0].focus();
        input[0].setSelectionRange(len, len);
      })  
    });
  }
}

Code in the component.html:

<input id="txtsearch"
  type="text"
  (blur)="showSsnMask = true"
  (click)="showSsnMask = false"
  [value]="ssnValue | mask: showSsnMask:9"
/>
Zhi Lv
  • 18,845
  • 1
  • 19
  • 30
  • I don't think this is an optimal solution. It uses jQuery, which now means there are two frameworks manipulating the DOM of the app. That said, `setSelectionRange` is a JS function that I must have overlooked. Using this, I refactored my code to set the carat on focus. Thanks for the heads up. – Griffin Apr 18 '19 at 15:34