Handling forms in Angular
Having looked at adding validations to the forms, let us see how we can go about reacting to specific validation errors. Consider the simple case of the registration of a user using their email. The form control for the email can have validations for email format and additionally a validation for checking if the email already exists in the system. The form building can be similar to what we did in the custom validator section earlier:
email: [null, Validators.email, Email.unique ]
In the template code, we could then check for the failure reason by using the hasError
method, which is present on both FormGroup
and FormControl
. We also used the touched
condition, so the check is made only if input has been touched by the user:
<div *ngIf="userForm.get('email').touched &&
userForm.get('email').hasError('unique')">
Email already exists
</div>
The hasError
method returns true, if the 'unique'
check returns a JSON having { unique: 'true'...