You can create a service with a function that you can use to know if the value of each field of the form is valid and return the corresponding error message
Create a validator.service.ts
service
import { Injectable} from '@angular/core';
import { FormGroup} from '@angular/forms';
@Injectable()
export class ValidatorService {
public errorMessage: string;
/**
* @summary Usada para saber si un campo es valido o no
* @param _field FormControlName ==> campo a validar
* @param _form FormGroup ==> Formulario al que pertenece el campo a validar
* @return boolean => true: válido | false = inválido
*/
public isValid(_field: string, _form: FormGroup): boolean {
if (_form.get(_field).invalid && _form.get(_field).touched) {
if (_form.get(_field).errors.required) {
this.errorMessage = "Campo requerido";
return false;
}
if (_form.get(_field).errors.minlength) {
this.errorMessage = "Mínimo" + _form.get(_field).errors.minlength.requiredLength + " caracteres";
return false;
}
}
return true;
}
}
In your module:
Import the service
Add it to providers
import { ValidatorService } from './_services/validator.service.ts';
providers: [ValidatorServicice]
In your component:
Import the service
Inject the service into the constructor method
import { ValidatorService } from '../../../../_services/validator.service.ts';
constructor(public _validator: ValidatorService) {}
In your view:
<form [formGroup]="fgTest">
<div class="md-form">
<input mdbInputDirective type="text" id="nombre" class="form-control" formControlName="nombre">
<div *ngIf="!_validator.isValid('nombre', fgTest)">
<span style="color: #f4516c;">
{{ _validator.errorMessage }}
</span>
</div>
<label for="nombre">Nombre</label>
</div>
</form>
It should be noted that in this way it was implemented only to show an error message, the first error message it finds.
Or the other option is to view part of the validations made by the isValid function and replicate it for each element of your form.