4
votes

I am trying to create a little form with validation inside a modal dialog. The dialog has a cancel button which should hide the dialog:

enter image description here

I've created a small project to verify it:

https://embed.plnkr.co/jF202JGxI0f7BjeKhL7A/

The name field has a validation which is triggered if the name is left empty. The input field gets focus when the dialog is shown.

The problem is now pressing cancel without entering any text.

The validation kicks in before the button's click handler is triggered. The result is that the error message is displayed. This moves the cancel button down and the click goes to nirvana.

You can verify this behavior by clicking the top part of the cancel button. If you click the bottom part everything works as expected (except that I would prefer not to show the validation message at all).

So... what I'd like to have:

Trigger validation if user

  • leaves the field by pressing tab
  • clicks on next field (in some other dialog with more fields)
  • clicks on ok / create metric
  • changes the field content

Trigger no validation if user

  • clicks on cancel
  • clicks outside of the dialog
2
Similar question, shows that this can happen in any form, not just inside a modal: stackoverflow.com/questions/45015403/… - rmcsharry
I have the same problem. I've tried doing type="reset" and type="button" on the Cancel button, but that does not solve the issue. The problem is that validations fire on the blur event of a field BEFORE the click handler fires for the Cancel button. - rmcsharry

2 Answers

0
votes

I think that your problem resides at the condition in your error label.

The property touched is triggered when the input has been visited. The property dirty is triggered when the input has been changed.

So you need to remove the touched condition, try replacing your error label code with this:

<label *ngIf="myForm.controls.name.errors && myForm.controls.name.dirty">

You can learn more about forms in the official documentation: https://angular.io/guide/forms

0
votes

I have faced same issue. The workaround I made on cancel button is, use (mousedown) instead of (click) to dismiss the model.