Angular Form Errors – A Declarative Solution
Most of Angular is different than Angular 1.x, but one of the idioms that stayed the same was the use of class names to identify form fields that had validation errors (e.g. ng-invalid, ng-dirty, ng-touched etc). By checking for different combinations of these classes, you can tell which fields are invalid, have been modified (“ng-dirty”), and had focus at some point (“ng-touched”). However, this had a tendency to lead to some rather verbose and messy view code just to show/hide a validation message:
<input type="text" formControlName="firstName"> <div> <div *ngIf="form.get('firstName').hasError('required') && form.get('firstName').touched && form.get('firstName').dirty"> First Name is required</div> </div>
As you can see, this is a lot of boilerplate code just to show a simple “required” message. And for every required field on the form – you’d need this same *ngIf condition. Fields with other validation rules would need additional *ngIf expression evaluations as well.
The ngxerrors package addresses the reactive form validation issue with a declarative syntax that is much more concise and readable than the above code. Here is what the above example looks like using ngxerrors:
<input type="text" formControlName="firstName"> <div ngxErrors="firstName"> <div ngxError="required" [when]="['dirty', 'touched']"> First Name is required</div> </div>
Passing the formControlName to the ngxErrors directive wires up the form field to the validation, and each nested ngxError block checks for a specific validation rule (e.g. required, pattern, minLength, and maxLength, as well as custom validators you write). Using the [when] directive you can control when the error message is displayed based on the corresponding ng- class name.
After trying out ngxerrors, I am finding it to be a nice solution for reactive form error handling and am currently using it on several projects.