I have a problem, I don't get the asynchronous validation with the reactive forms in angular. I get to keep the query active when writing about the input and it brings me results but I can't send the error in the html. I am new in angular and I don't know what I would be missing in the code.
Component.ts
this.registroForm = this.fb.group({
nombre: ["", [Validators.required, Validators.pattern("[a-zA-Z ]*")]],
apellido: ["", [Validators.required, Validators.pattern("[a-zA-Z ]*")]],
username: [
"",
[Validators.required, this.validateEmailNotTaken.bind(this)]
],
email: ["", [Validators.required, Validators.pattern(this.emailPattern)]],
telefono1: [
"",
[
Validators.required,
Validators.maxLength(10),
Validators.minLength(10),
Validators.pattern("[0-9]*")
]
],
condiciones: ["", [Validators.required]]
});
My Validation Function: Checks every time I write in the input, the server responds to me in the following way, when the name exists in the BD it brings me the data of that in an json array, but an empty array that is why the data.length. So if it is equal to one it should show the error. But the input writes anything and it is placed in red without showing a specific error (for the validation of material angular) and apart it does not show the error in whether it exists or name not available.
validateEmailNotTaken(control: AbstractControl) {
let username = {
user: control.value
};
return this.authService.buscarUserUsername(username).subscribe(
(data: any) => {
console.log(data.length);
if (data.length === 1) {
return { userNameExists: true };
}
},
err => {
console.log(err);
}
);
HTML
<mat-form-field appearance="outline" color="accent">
<mat-label>Usuario</mat-label>
<input formControlName="username" matInput placeholder="Nombre de usuario">
<mat-error *ngIf="registroForm.controls['username'].errors?.required">Este campo es obligatorio
</mat-error>
<mat-error *ngIf="registroForm.controls['username'].errors?.pattern">No es un nombre de usuario valido
</mat-error>
<mat-error *ngIf="registroForm.get('username').errors?.userNameExists">
Nombre de usuario no disponible </mat-error>
</mat-form-field>
username: ["", Validators.required, this.validateEmailNotTaken.bind(this)]