Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Style Validation in Angular 2 Forms

    2 - 6

    Inputs using Angular 2’s ngModel automatically apply style classes of .ng-valid and .ng-invalid each time the input’s validity changes. These classes allow you easily add your own styles simply by declaring the styles in your Component decorator.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    If you use the dev tools to select one of the inputs inside of your form, you'll notice these classes NG untouched, NG pristine, and NG valid. Let's focus on NG valid, because if I change this input to be invalid, this field is required, you'll see that this now has NG invalid instead of NG valid.

    What that allows us to do is to style these fields with our own custom styles based on those classes. If I add a style of NG invalid and I say it's a border, it's a three pixel solid red, and I hit save. You'll see now we're green. If I delete this, this field becomes red.

    If I go ahead and duplicate that so we have an NG valid class, we'll say this one is green and I hit save, you'll see it starts as green. In fact, they're both green. If I delete this, this one turns red and this one's green.

    Each input inside of your form is going to provide these convenient validity classes you can use, to simply create your own CSS classes and apply a style based on whether it's valid, or based on whether it's invalid.