Detecting an error on an input field with named references

So far, we have settled for looking at the form reference when we want to know whether our form is valid or not. We can do a lot better here, we can detect whether a specific input control has an error. An input control may have more than one validator, which means we might have more than one validation error to show as well. So how do we detect that? There are a number of steps to be taken to accomplish this:

We need to:

  1. Create a view reference for each input element and also assign it the value ngModel.
  2. Give each element a name attribute.

Let's update our form code and add view references and name attributes according to the preceding steps:

<form #formPerson="ngForm">
<input #firstName="ngModel" [(ngModel)]="person.name" id="name"
name="name" placeholder="first name" required>
<input #surName="ngModel" [(ngModel)]="person.surname" id="surname"
name="surname" placeholder="surname" required>
<button *ngIf="formPerson.form.valid">Save</button>
</form>

Once we have done the pre-work, it is time to talk about what errors we can detect. There are two types of errors that are of interest:

  • A general error, which is an error that says there is something wrong on the input control, but doesn't specify what
  • A specific error, which will indicate the exact type of error, for example, the value is too short

Let's start with a general error:

<input #firstName="ngModel" [(ngModel)]="person.name" id="name"
name="name" placeholder="first name" required>
{{ firstName.valid }} // an empty field sets this to false

We use our view reference firstName and query it for its valid property, which indicates whether an error exists.

Now for the other more detailed error. To detect a more detailed error we use the errors object on our view reference and output the whole object using the JSON pipe:

{{ firstName.errors | json }}  // outputs { required: true }

This means we can suddenly find out whether a specific error has been set and we can therefore decide to display a conditional text based on a certain error being present, like so:

<div *ngIf="firstName.errors && firstName.errors.required">
First name is a required field
</div>

Other specific errors will populate the errors object, and the only thing you have to do is know what the error is called. When in doubt, output the errors object using the JSON pipe to find out what the validation error is called for a certain validator, and what validation error values go with it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset