Skip to content

Instantly share code, notes, and snippets.

@dcagnetta
Created September 14, 2022 13:23
Show Gist options
  • Save dcagnetta/d50e12bf6a06ef12ade0ea8dafb3cf26 to your computer and use it in GitHub Desktop.
Save dcagnetta/d50e12bf6a06ef12ade0ea8dafb3cf26 to your computer and use it in GitHub Desktop.
Angular Async Validation
this.form = this.formBuilder.group({
code: ['',
[Validators.required, Validators.pattern('^[A-Za-z0-9]{4}')],
this.asyncCodeValidator.validate(),
]
});
@Injectable({ providedIn: 'root' })
export class AsyncCodeValidatorService {
constructor(private codeService: CampaignService) {}
validate(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return this.searchCode(control.value).pipe(
map(result => {
return result.available ? null : { notUnique: 'Action code not unique' };
})
);
};
}
searcCode(code: string): Observable<CodeValidate> {
return timer(500).pipe(
switchMap(() => {
return this.codeService.validateCode(code); // return Observable<CodeValidate>
})
);
}
<form [formGroup]="form">
<input type="text" formControlName="code">
<p style="color: red" *ngIf="form.get('code').errors?.notUnique">code not available</p>
</form>
}
https://stackoverflow.com/questions/68034096/angular-asyncvalidatorfn-works-only-onblur-and-not-on-keypress-event
Not updateding in the DOM
remove: changeDetection: ChangeDetectionStrategy.OnPush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment