Is there a way to pass the validations that are done on the fields of a reactive form (in the .html) to the component file (.ts). So that the template is clean and without the logic.
For example, I have a form with the following logic
<div class="form-group">
<label for="correo">Correo</label>
<input formControlName="correo" type="text" class="form-control" id="correo" placeholder="Ingrese su correo">
<small id="nombreHelp" class="form-text text-muted">No mostraremos tu correo.</small>
</div>
<div class="errorCodigo"
*ngIf="formulario.controls.correo.touched &&
formulario.controls.correo.hasError('pattern')">
El formato del correo no es valido
</div>
<div class="errorCodigo"
*ngIf="formulario.controls.correo.touched &&
formulario.controls.correo.hasError('required')">
El campo es requerido
</div>
How can I move the validations that are shown with the ngIf to the component, so that it is the one that returns the corresponding error?
I found the following way
1) In the component (.ts file) I declare a json array with the error messages, for example:
The properties 'minLenght', 'required' and others are the validations that I declare with the form. See the following code
2) Create an auxiliary function that receives the name of the input (for example 'Social Reason'):
The function receives the name of the input and queries, if it was touched and there is an error, it searches the json array (the one from step 1) to return the corresponding error message.
3) In the html file, we make a call like this:
This will allow us to display the custom error messages we defined.
Edit
If you are working in angular material, in the html you should show the errors like