Reputation: 89
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 class="form-group">
<input type = "text" class="col2" formControlName="pinCode"
[(ngModel)]="pinCode" required (keyup.enter)="generatecityDetailArray()" maxlength="6" />
<div *ngIf="f.pinCode.invalid && f.pinCode.touched"><strong class="text-danger" *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.
Upvotes: 0
Views: 2242
Reputation: 108
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)="cityDetailForm.get('pinCode').invalid ? $event.preventDefault() : generatecityDetailArray()"
This is if you have only one validator setup for the pinCode formControl.
If you have multiple make the check cityDetailForm.get('pinCode').errors?['required']
.
Also this is assuming that cityDetailForm
is your formGroup. I previously thought it was simply f
, because of the ngIf
check on your div
.
It would be best to have a getter in the component for this case, so it would be something like:
get isCityDetailInValid(): boolean {
return this.cityDetailForm.get('pinCode').errors?['required'];
// or this.cityDetailForm.get('pinCode').invalid;
}
Then your template would simply be:
(keyup.enter)="isCityDetailInValid ? $event.preventDefault() : generatecityDetailArray()"
Upvotes: 0
Reputation: 6878
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
Upvotes: 0
Reputation: 6878
why not just start method generatecityDetailArray()
by
if (!this.pinCode) {
return;
}
Upvotes: 1