I am currently working on a form in Angular/Typescript of several fields (more than 10 fields), and I wanted to manage the errors more properly without duplicating code in my html page.
Here is an example of a form :
<form [formGroup]=myForm>
<label>Name</label>
<input type=text formControlName=name>
<p class=error_message *ngIf=myForm.get('name').invalid && (myForm.submitted || myForm.get('name').dirty)>Please provide name</p>
<label>Lastname</label>
<input type=text formControlName=lastname>
<p class=error_message *ngIf=myForm.get('lastname').invalid && (myForm.submitted || myForm.get('lastname').dirty)>Please provide email</p>
<label>Email</label>
<input type=text formControlName=email>
<p class=error_message *ngIf=myForm.get('email').hasError('required') && (myForm.submitted || myForm.get('email').dirty)>Please provide email</p>
<p class=error_message *ngIf=myForm.get('email').hasError('email') && (myForm.submitted || myForm.get('email').dirty)>Please provide valid email</p>
</form>
In my case, I have two types of validation for my form :
- Html validation : required, maxSize, ... etc.
- Back validation : For example, invalid account, size of loaded file, ... etc.
I try to using a directive as mentioned here
<form [formGroup]=myForm>
<label>Name</label>
<input type=text formControlName=name>
<div invalidmessage=name>
<p *invalidType='required'>Please provide name</p>
</div>
<label>Lastname</label>
<input type=text formControlName=lastname>
<div invalidmessage=lastname>
<p *invalidType='required'>Please provide lastname</p>
</div>
<label>Email</label>
<input type=text formControlName=email>
<div invalidmessage=email>
<p *invalidType='required'>Please provide email</p>
<p *invalidType='email'>Please provide valid email</p>
</div>
</form>
But even with this solution the code is always duplicated and no ability to handle both types of validation.
Do you have another approach ? Is use components appropriate in this case ? If yes, how can do it.
Thank you in advance for your investment.