I am working with Angular reactive forms and async validation and instead of a normal value I want to send Json file for validation.
My form Looks like
createGoogleCloudForm = new FormGroup(
{
name: new FormControl('', [Validators.required, Validators.pattern(RegexUtil.cloudName)]),
organizationId: new FormControl(''),
config: new FormControl(),
//zones: new FormControl({ value: '', disabled: true }, Validators.required),
},
undefined,
//[GoogleCloudCredentialsValidator.checkGoogleCloudCredentials(this.cloudCredentialsCheckerService)]);
My HTML file looks like
<form class="form" [formGroup]="createGoogleCloudForm" (ngSubmit)="createGoogleCloudCredential()">
<div class="image-upload">
<label for="background-upload" class="button button--outline display--inline-flex">Choose Config File</label>
<span class="file-name">
{{ googleCloudFormData?.get('config')?.name | truncate: 40:'...'
}}
</span>
<input
type="file"
id="background-upload"
class="hidden-input"
formControlName="config"
(change)="fileChange($event.target.files, 'config')"
/>
</div>
</div>
<div class="display--flex justify--content--end">
<button class="button button--primary display--inline-flex" type="submit" [disabled]="!createGoogleCloudForm.valid">
<svg-icon key="circle-plus"></svg-icon> Add Cloud Credentials
</button>
</div>
</form>
The file change method is like
fileChange(files: File[], controlName: string) {
console.log(files);
if (files && files.length > 0) {
this.googleCloudFormData.append(controlName, files[0]);
console.log('adding');
this.createGoogleCloudForm.setAsyncValidators([
GoogleCloudCredentialsValidator.checkGoogleCloudCredentials(this.cloudCredentialsCheckerService),
]);
}
}
The Async Validator is
static checkGoogleCloudCredentials(cloudCredentialsCheckerService: CloudCredentialsCheckerService): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> =>
// half a second delay to prevent BE requesting after each user's key stroke
timer(500).pipe(
switchMap(() => cloudCredentialsCheckerService.checkGoogleCloud(control.get('config').value)),
map(() => null),
catchError(() => of({ invalidGoogleCloudCredentials: true })),
);
}
and the service
checkGoogleCloud(file: File[]) {
return this.http.post(`${this.baseUrl}/google`, { file });
}
The problem is when I upload the file the async validator does not get fired, I want to send the file with the request.
Any ideas?