The form validations play a significant role in web applications that have heavy forms. With validations, we achieve two things:
In this article, we will see both.
On every keystroke, the HTML elements emit an input event; this triggers the form validators' execution and updates the FormModel. We can say in a nutshell that on every keystroke, the value and the validity are re-calculated.
There is a property in the AbstractControl classes (FormControl, FormGroup, FormArray) allowing us to change the default behavior. The options are:
In line 21, we see how to use the updateOn option, and in the video below, we see the result.
Display the error messages on submit
The previous section's code block has two FormControl instances, and each one has a required validator. We often have to find a way to display the error messages to the user only when the submit button is fired. Lucky us! In Angular Reactive Forms, this comes for free and is very easy to use.
Let's see some code parts of the [formGroup] directive.
What we see in line 53, is a listener for the (submit) event, which is handled by the method "onSubmit".
It is also useful to note that we can use the [formGroup] public properties on our templates, which are available to us because of the exportAs in line 54.
How about the onSubmit event handler code? Let's have a look at it.
In line 242, we see that the submitted property is assigned with the value true. And guess what! This property is public; hence, we can use it in our template! 🎉
We are one step away from seeing how to use the submitted property.
In line 2, we declare a template reference variable, and we assign it with the ngForm, which is the name formGroup uses to export itself.
We can now use set the class "is-invalid" only if the form is submitted and the corresponding control is invalid. We do this in lines 12 and 28.
And that's it! Let's see what the result of this code is.
Thanks for reading this article 🙏