Automatic Angular template- form messages
Writing all error messages for Angular’s template-forms can be a bit exhausting. Today we will spend a little time writing code, that will save us a lot of time later when we would have to write all those messages.
Let’s start with a basic form
We will be using ngx-translate (to store all text into a single file) along with bootstrap@5.0 and animate.css.
We have created a simple form with a single field — username, it has 3 validation rules — required, minlength and maxlength, and have created an error message for all of them. You can see, that the code starts to grow really fast and it would essentialy be copy-pasted when adding fields or new forms.
Let’s wrap the messages into a separate component
We have generated a new error-messages component. All we need to do is to provide the component with our NgModel and move our error logic there.
Great, now we have successfully reduced the number of copy-paste for every field. Let’s continue.
Do we always have to create the component manually?
No, we don’t. Let’s use directives for that.
All we need to do is to use the same selector as the NgModel Directive and upon creation create our error-messages component.
Now we can finally remove our component from the form. All errors are displayed automatically and we can focus on the more interesting subjects.
Conclusion
We have successfully reduced the number of copy-pasted code in our application and ensured, that any change in the error-displaying logic or styles will made in one place for our entire app.
Warning
You should probably add a flag attribute to your directive for any instances, where you do not want to display the errors.
GitHub repository
For reference, our project can be found at https://github.com/2bad2furious/ng-form-control-errors