Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Check ngModel Validation in Angular 2

    John LindquistJohn Lindquist

    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.

    angularAngular
    2 - 6
    Code

    Code

    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
    Transcript

    Transcript

    00:00 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.

    00:16 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.

    00:33 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.

    00:46 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.

    Discuss

    Discuss