Handle Angular form control validation errors using pure pipe

Max Synyuk
2 min readMay 12, 2021

Searching for different ways to handle form control validation errors, I’ve found, that there are a lot of solutions to achieve this, but sometimes these solutions are so complex, that I’ve decided to investigate this “issue”.

Why pipes? It is the best and the easiest solution, that possibly could be, I think! I’ve tried different ways to handle errors including component and service implementation, but in the first way, we will get a huge Html, that so uncomfortable to work with; and in the second we will have to call a method in a template and everybody knows what would be in that case. So, let’s dive more deeply into pipe form control error handling. To have a more beautiful view I’ll be using Angular Material.

First of all, let’s create our simple FormControl with a required validator.

And Html:

As expected, we don’t have any error notifications:

So let’s add an error container to mat-form-field, and step by step will be creating our pipe.

What’s happening here? We are passing error keys to our pipe and take the first key of an error. Then we have to create a private object of all our error keys to get the needed message:

Also, we’ve added a check for existing errors where we return a string from our object. And the final step is to add our pipe into Html:

Voila! That’s it. The method called only once when an error will change to another.

So, the next step required from you is only to expand your object, created in pipe with validators error keys:

Hope this article was helpful for you. Please, leave feedback :)

--

--

Max Synyuk

I'm a Front-End Angular developer at Reenbit company