Input 'touched' in angular validation is blocking method execution

Viewed 181

I noticed when using this kind of validation:

<label>Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touched && f.password.errors }" />

  <div *ngIf="f.password.touched && f.password.errors" class="invalid-feedback">
    <div *ngIf="f.password.errors.required">Password is required</div>
    <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
  </div>
<div class="form-group">
  <button class="btn btn-primary" (click)="alertX()">sdf</button>
</div>

When I focused the input and then click the button, the method 'alertX()' is not executed I think it is because the state for the input changes to touched=true before the alertX(), (this happens sometimes not always but is kinda annoying for UX) any advice how to avoid this behaviour would be appreciated... Example of method not executed when input was focused the button was clicked

1 Answers

According to MDN Docs:

click fires after both the mousedown and mouseup events have fired, in that order.

In your example, clicking on the button causes the mousedown. This fires the validation immediately and there is an error under the input.

This moves the button a little lower and the mouseup is no longer on the button! So the click event doesn't fire since you didn't mouseup on the button.

Workaround:

  <button class="btn btn-primary" id="btnSubmit" (mousedown)="alertX()">Register</button>

Register a EventListener on mouse down rather than a 'click' event to fire.

Working Demo on Stackblitz

Related