Home > Back-end >  How to call a function after typing six character length in Angular
How to call a function after typing six character length in Angular

Time:11-20

I want to call a function rather than on button click , when user will type maximum 6 digits in input box from reactive form in Angular. How can I achieve this ?

In HTML:-

<form style="margin-left: 17px;" [formGroup]="otpForm" (ngSubmit)="submitOtp()">
 <mat-form-field appearance="outline">
       <input matInput placeholder="6 digit OTP" formControlName="otp"  numbersOnly
        maxLength="6" minLength="6" required autocomplete="off">
 </mat-form-field>
</form>

TS file

submitOtp(){ // call verify OTP API}

CodePudding user response:

Please try like this, add myFunction call at input event

<form style="margin-left: 17px;" [formGroup]="otpForm" (ngSubmit)="submitOtp()">
 <mat-form-field appearance="outline">
       <input matInput placeholder="6 digit OTP" formControlName="otp"  numbersOnly
        maxLength="6" minLength="6" required autocomplete="off" (input)="myFunction()">
 </mat-form-field>

In .ts file

myFunction = () => {
  if(this.otpForm.controls.otp.value.length === 6) {
  // your logic operation
  }
}
</form>

CodePudding user response:

You need to add (input) event on input tag because it will track every single character on that input field.

For Example

otpForm: FormGroup;

constructor(private formBuilder: FormBuilder) {
  this.otpForm = this.formBuilder.group({
    otp: new FormControl('', Validators.required),
  });
}

inputHandle(event) {
  var number = event.target.value;

  if (number.length >= 6) {
    this.submitOtp();
  }
}

submitOtp() {
  console.log('call OTP API');
}
<form [formGroup]="otpForm" (ngSubmit)="submitOtp()">
  
        <input matInput placeholder="6 digit OTP" formControlName="otp" class="form-control" numbersOnly
         maxLength="6" minLength="6" required autocomplete="off" (input)="inputHandle($event)">
  
 </form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Here you can play or check

CodePudding user response:

otpForm.controls['otp'].statusChanges.subscribe(status => {
  if (status === 'VALID') {
    // call function here
  }
});

You will need to make sure the validators are on the reactive form and not just the html:

otp = new FormControl(
  null,
  [Validators.required, Validators.minLength(6), Validators.maxLength(6)]
)
  • Related