I have been using reactive form in my Angular project in many places and last week we decided to optimize our code a bit. During code review I have found an issue regarding showing form validation messages in HTML.
So I have used below code to show validation error messages:
<form [formGroup]="form">
<div>
<input formControlName="firstName">
<div *ngIf="form.controls.firstName.errors && (form.controls.firstName.touched || form.controls.firstName.dirty)">
This field is required
</div>
</div>
</form>
It seems fine, but what if I replace form.controls.firstName.errors with !form.controls.firstName.valid See below:
<form [formGroup]="form">
<div>
<input formControlName="firstName">
<div *ngIf="!form.controls.firstName.valid && (form.controls.firstName.touched || form.controls.firstName.dirty)">
This field is required
</div>
</div>
</form>
I couldn't see any difference at all but in my team some of team mates has opinion that we should use !form.controls.firstName.valid and we had long discussion on this small issue. I still didn't convince with my team mates. For me if form has an error then it's status will be invalid or form is invalid because it has an error.
Could anyone suggest me which option we should follow and is correct fundamentally.
Many thanks in advance.