Created
September 14, 2022 13:23
-
-
Save dcagnetta/d50e12bf6a06ef12ade0ea8dafb3cf26 to your computer and use it in GitHub Desktop.
Angular Async Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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