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.


    Check ngModel Validation in Angular 2

    John LindquistJohn Lindquist
    2 - 6

    Checking the validity of an Angular 2 input using ngModel is simply a matter of getting a reference to the ngModel itself. You get the reference by using the #ref syntax, assigning it a name, then ngModel will check all of the validity rules for you.



    Become a Member to view code

    You must be a 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




    We can make the input required by saying required. Then if there's nothing in here, this field will be marked invalid. Right now there's no way for us to know in our template whether this is invalid, because this is just bound to the value of the input, not the validity of the input.

    To get the validity we need to access the NG model itself in the template. We can do that by creating a reference to the ng-model. That's going to look something like this. I'm going to call this user name ref, then assign that to the ng-model directive.

    In my binding I can actually access the user name ref.valid. Hit Save, and you'll see that now this is valid because it's required. If I could lead everything it's not valid, because this requires something.

    If I type this is true, delete, it's false, because this is a reference to the ng-model it knows if this is valid or invalid.