Implementing custom feedback to form validation with Angular

Yesterday, we saw that Angular uses six different CSS classes (actually, eight – I didn’t mention ng-pending, which is the temporary state when async validation is being performed, and ng-submitted, which applies to the form element only).

Today, let’s see how we can customize the feedback displayed to the user beyond CSS classes. The nice thing about Angular validation properties is that they’re not just available as CSS classes. They are also available as public properties on the ngModel and the ngForm directives used in our form.

We can access such properties using template reference variables to access the exported values of these directives as follows:

The above code would result in the following rendering:

Of course, displaying true or false is not very user-friendly. Instead, we can use *ngIf and make the experience a little more polished:

Which looks like this:

We can apply the same idea to the form element and decide to disable the submit button as long as the form is invalid:

Or we could even hide the button as long as the form is invalid:

You get the idea. As simple as those validation properties are, they enable many possible different customizations of how we display validation feedback and hints to the user.

You can play with my code example on Stackblitz.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.