In my previous article, we talked about how to show form errors on submit.

When your form start to grow, you can end up with something like this:

If you are coding all your forms like that, you are probably Psychopath 😜 (just kidding)

The template is verbose; it’s hard to understand what’s going on and you are not DRY.

What if we could write something like this:

I think that looks a lot better ( later you will see how we can be even cleaner than that ). So let’s create the control-errors component.

We need two Inputs :

The control name. The errors Object.

Next, we can ask Angular to give us the ngForm instance in our component via dependency injection with the Host decorator. ( we are using also the Optional decorator to protect our code )

That’s the equivalent of doing this in our template:

<form #myform="ngForm"></form>

If you are still confused from where this NgForm is coming, In a nutshell, it’s just a built-in directive with a selector that points to almost any form tag.



selector: ‘form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]’

})

export class NgForm extends ControlContainer implements Form {} @Directive ({selector: ‘form:not([ngNoForm]):not([formGroup]),ngForm,[ngForm]’})export class NgForm extends ControlContainer implements Form {}

Ok, now we have the form instance let’s get the errors.

Our getter functionality is straight forward:

Find the current control in our form instance. Loop over the Input errors keys. Check with the hasError() method if we have an error with the same key. Show the error.

That’s all! You can play with the plunker.