Home > Software engineering >  How to disable enter key in angular if condition does not match?
How to disable enter key in angular if condition does not match?

Time:12-24

If input is null enter key should not call the function "generateCityDetailArray()" means it should be disabled, otherwise it should call the function "generateCityDetailArray()". How to achieve this?

<div >
          <input type = "text"   formControlName="pinCode" 
          [(ngModel)]="pinCode"  required (keyup.enter)="generatecityDetailArray()" maxlength="6" />
          <div *ngIf="f.pinCode.invalid && f.pinCode.touched"><strong  *ngIf="f.pinCode.errors?.required">Please enter the value!</strong></div>
</div>

Now, If I click enter in textbox, it is calling "generateCityDetailArray()" even when input is null. What required is if input is null and If enter is clicked then it should give a message like "Plz Enter pincode", "generateCityDetailArray()" should not be called when input is null.

CodePudding user response:

why not just start method generatecityDetailArray() by

if (!this.pinCode) {
  return;
}

CodePudding user response:

The suggestion of starting the generatecityDetailArray() method with a check if you have a value of pinCode is a great option.
If you want to have your check performed in the template, you can also do the following:

(keyup.enter)="pinCode ?? generatecityDetailArray()"

CodePudding user response:

if you have form control on input you can launch method only when input have no error

(keyup.enter)="pinCode.errors ? '' : generatecityDetailArray()"

If you want to display message to say you have to enter pincode you can use follwing syntaxe

 <div *ngIf="pinCode.errors?.['required']">
    Please Enter pincode.
  </div>

in your class you have to define getter and setter of the form control

get pinCode() { return this.cityDetailForm.get('pinCode'); }

here the doc about validators https://angular.io/guide/form-validation

  • Related