I'm implementing my own components for my Angular project. I'm trying to be smart about implementing validation messages.
My current implementation has multiple boolean inputs for "required", "invalidFormat" and such.
What I want to do is, user form control validations inside my custom inputs. So I want something like this:
<div *ngIf="formcONTROL.errors?.['required']">
This field is required
</div>
And I want that inside the custom component and for multiple validations, such as format, minLength etc.
But I want to do that without having a form control input. My custom input class implements ControlValueAccessor
so it works inside a reactive form but I want to know is there any way to access the control that is bound to the component I'm working on?
Also is that considered best practice? It seems to me like the best approach to error handling. I just want to provide formControlName
and let the component deal with validation under the hood.
I tried implementing using boolean input fields and it works, but it requires of me to do a lot of code repetition such as this:
<custom-input type="email"
formControlName="email"
[label]="t('email.title')"
[requiredError]="formGroup.controls['email'].errors?.['required']"
[formatError]="formGroup.controls['email'].errors?.['email']"
[required]="true">
</custom-input>
<custom-input type="password"
formControlName="password"
[label]="t('password.title')"
[requiredError]="formGroup.controls['password'].errors?.['required']"
[required]="true">
</custom-input>
And I would like to just pass formControlName
and that would be enough for handling validation