Angular form validation activated before cancel button pressed

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

enter image description here

I created a small project to test it:

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

There is a confirmation in the name field, which is triggered if the name is left blank. The input field receives focus when the dialog is displayed.

Now the problem is canceled without entering any text.

Validation is triggered before the button click handler is called. As a result, an error message is displayed. This moves the undo button down and the click jumps to nirvana.

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

So ... what I would like:

Trigger check if user

  • leaves the field by clicking the tab
  • clicks on the next field (in another dialog with more fields)
  • clicks on ok / create metric
  • changes the contents of the field

Do not run check if user

  • undo clicks
  • clicks outside the dialog
+2


source to share


2 answers


I think your problem is the condition in your error label.

The affected property is triggered when the input is visited. Property pollution is triggered when the input has been changed.

So, you need to remove the affected condition, try replacing the error label code like 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


source


I faced the same problem. A workaround I did on the button cancel

: use (mousedown)

instead (click)

to close the model.



0


source







All Articles