Angular 2’s ngModel provides error objects for each of the built-in input validators. You can access these errors from a reference to the ngModel itself then build useful messaging around them to display to your users.
[00:00] To check on specific errors from our NG model, let's go ahead and check errors instead of just validity. Right now we have no errors. When I delete everything because it's required, it'll give me an object.
[00:13] To just debug this, we can throw in a pipe JSON. Now instead of just that object, it'll give us the actual object. Right now it's null because there are no errors.
[00:24] When I delete this, you'll see that it has required true on there. If I do something like add min length of three and hit save, it's null because there's no errors.
[00:35] I delete everything, required is true. When I add one character, you'll see that min length actually gives you back an entire object with the data required length of three, actual length of one. You could write an error message based on that.
[00:48] To show these off, let's do a div saying this field is required. We'll put an NG if on this which will only show up if username ref.errors.required. What you're going to see is this will show up. This field is required.
[01:06] That's because we're actually getting an error here in the console. To explain what it's saying, property required of null, that means that this object errors is null. When it tries to access required, it simply can't do that because errors itself is null.
[01:23] What you can do in this situation is just put a question mark here to mark that this is possibly null so don't try and evaluate this if errors is null. That way when we save, you'll see we get the null message from this div which is our debugging.
[01:39] When I delete this, my this field is required shows up and my debugging says required true. This is only going to show this if that required is there and errors exist.
[01:52] We could do a similar thing with min length. Min length, I'll say this field must be longer than three characters. I'll hit save. You'll see our debugging says null. I'll delete everything. This field is required. I'll put in one character. It'll say this field must be longer than three characters because this object evaluates to true.
[02:15] I can actually use these two properties, required length and actual length, in my message which I'll do my copying this whole thing here. I'll say this field must be longer than, and I'll put the curly braces in. I'll paste minlength.requiredlength, and then .youonlytyped [for binding actual length] . I'm going to get rid of the debugging because that'll get pretty busy with that on the screen. I'll hit save.
[02:46] You'll see if I delete everything, it'll say this field is required. If I type A, this field must be longer than three characters. You only typed one. You only typed two. Error message gone.