Home > Software engineering >  angular shift input field cursor at beginning after 4 digits typed
angular shift input field cursor at beginning after 4 digits typed

Time:12-14

I need some assistance in the rear scenario of the reactive form input field. I have a field name that enters the last four digits of the SSN after filling it out with last four digits an API call is triggered to check valid SSN if it gives success then we pass the last four digits of the SSN and if it gives failure response then we have to move the cursor of the field at the beginning to enter the first 5 digits of SSN with actual SSN format like 123-45-6789.

For example, if the user enters 6789 and API sent a failure response then the input field cursor moves at the beginning and now if a user enters the next digit it shows 5-6789, and after that 45-6789, 3-45-6789, and so on till it doesn't show like 123-45-6789.

HTML code.

<input formControlName="ssn" type="text"
                            name="ssn" [imask]="ssnMask"
                            (keyup)="isSSNCorrect($event.target.value)" />

component.ts

this.ssnMask = "0000";

public isSSNCorrect(ssnNumber: string) {
      if (ssnMask == '0000') {
        if (ssnNumber.length === 4) {
          this.service.checkSSN(ssn).subscribe(
            res => {
              if (res.success) {
                console.log('success');
              } else {
                this.ssnMask = "000-00-0000"
                this.atBeginning();
              }
            }, (err) => {}
          );
        }
      }
  }

atBeginning() {
    div.nativeElement.setSelectionRange(0, 0);   
}

The above code does not shift the cursor at the beginning if I remove the imask then it shifts the cursor at the beginning but in that case, it shows without SSN format.

I attached the below link as a reference, in this, if I enter 4 digits and click on the test button then I want cursor shifts at the beginning of the input field and the next input takes the assigned imask format i.e 123-45-6789.

stackblitz example

CodePudding user response:

Could you try the below code, where set selection seems to work fine?

import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <input #input [ngModel]="value" [imask]="mask">
  <button (click)="click()">test</button>

`,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  @ViewChild('input') input: ElementRef<any>;
  name = 'iMask';

  maskToDot = {
    mask: '000-00-0000',
    scale: 2,
  };

  mask = {
    mask: '0000',
    scale: 2,
  };

  value: string = '';

  ngAfterViewInit() {
    console.log(this.input);
    // setCaretPosition(this.input.nativeElement, 3);
  }

  click() {
    this.mask = this.maskToDot;
    setTimeout(() => {
      this.input.nativeElement.setSelectionRange(0, 0);
      this.input.nativeElement.focus();
    });
  }
}

forked stackblitz

  • Related