Reputation: 939
I have an input field which I want to validate.
I am using a custom validator to check the validity of that input field value.
In the custom validator, I am making a rest call to an endpoint with the input field value to check if the entered value is valid.
The issue is the httpClient get call works in an async way, by the time the validation results are returned from the rest API. The input field validators come out and validation does not work per expectation.
Is there a way to make http call synchronously.
my httpClient call code inside a custom validator:
labelNameValidators.ts:
import {FormControl } from '@angular/forms';
export function labelNameValidators(control: FormControl) {
if(control.value!=null) {
this.labelService.checklabelNameFormat(control.value)
.subscribe(
(data) => {
if (data === 'true') {
console.log('success', data);
return {'labelMsg': { 'message' : data}};
}
else {
console.log('failure', data);
return {'labelMsg': { 'message' : data}};
}
},
(err) => {
console.log('error', err);
return null;
}
)
}
}
Label.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';
@Injectable({
providedIn: 'root'
})
export class LabelService {
private nameFormatCheckApi = environment.nameFormatCheckApi;
constructor( private http: HttpClient ) { }
checklabelNameFormat(name: string){
return this.http.get(this.nameFormatCheckApi + '?name='+name);
}
}
Upvotes: 0
Views: 1130
Reputation: 7490
You can use async validators for your case.
this.form = new FormGroup({
fieldExample: new FormControl(
null, Validators.required, asyncValidator())
});
here you are a live demo using async validators with template-driven forms and reactive forms.
https://stackblitz.com/angular/bbdorarjxea
Upvotes: 4