I want to create custom component for input text but I don't know how can I bind validation of each input field to custom component. Is there any way to set errors of each field as array of objects like below
<app-custom-input
formControlName="username"
label="Username"
[errors]="[
{ type: 'required', message: 'is required' },
{ type: 'minlength', message: 'min length error' }
]"
></app-custom-input>
In fact, I want to write reusable components that have different validations, for example, one field is required and another field has a length condition.
Step by step.
When we make a custom form control with validate the function validate should return or an object or null -if no errors-.
See that return an object with an unique property "error" that is an array of errors.
This error is an error not of the inner control -you input inside the custom-input- else the
FormControldeclared in "parent". So, to iterate over this error inside the custom form control we need "get it".Generally you use the constructor
But, as we have a validate function simply we declare, and give value to it in validate function
The last is iterate over this errors
Your forked stackblitz
NOTE: See that you needn't add the
validatorsto yourFormControlsIn your code:
update to only send if reuired we need use some like