For the past few days, I've been struggling to implement async validation with no success from various tutorials and solutions!
Service code-
getUserIdToCheckDuplicate(userId:any):Observable<any>{
const url = ``; //url goes here
return this.http.get<any>(url);
}
Component code-
ngOnInit(): void {
this.form = this.fb.group({
userId: ['', [Validators.required],[this.validate]]})
}
validate(control: AbstractControl): Observable<ValidationErrors | null> {
console.log(control.value);
return of(control.value)
.pipe(
delay(10),
switchMap((value) =>
this.userService.getUserIdToCheckDuplicate(value).pipe(map(x => {
return x.exists ? { exists: true } : null;
}))
)
);
}
Html code-
<mat-form-field appearance="outline" fxFlex="1 1 calc(25% - 10px)" fxFlex.lt-md="1 1 calc(25% - 10px)"
fxFlex.lt-sm="100%" fxFlex.xs="100%" class="from-color" *ngIf="!data">
<mat-label class="label-padding">User ID</mat-label>
<input class="label-padding" formControlName="userId" matInput placeholder="User ID" required />
<div style="color: red; font-weight: bold;" *ngIf="userId.errors?.exists">Already
Exists !</div>
</mat-form-field>
In the console- console error
As I type in the input field, every keystroke prints the value, but then reports value is undefined!
What could be causing this error? How can it be resolved to ensure proper functioning of the async validator?
Any assistance in tackling this issue would be greatly appreciated.