简体   繁体   中英

Angular FormGroup validation input file upload

I have problem with form input validation for the file upload. how do i validate formControle input when file upload is empty. How do i set the value inside selectFile so that when file input is empty the validation message which i get from server response will be shown.

i get the response messages from server for the other field Name and Familyname this is becouse i use formControlName inside Html and this works fine. But i can't use formControlName attribute inside input field for the file upload.

How do i get validation response message for file input field with out using formControlname?

html code

 <input type="text" placeholder="Name" formControlName="name" class="form-control" matInput />
 <span *ngIf="inputErrorMessage?.name">{{inputErrorMessage.name}}</span>
              
<input accept="*" type="file" (change)="selectFile($event)">
<span *ngIf="inputErrorMessage?.file1">{{inputErrorMessage.file1}}</span>

component.ts code

constructor(private uploadService: FileuploadService) {
    this.form = new FormGroup({
      name: new FormControl('' , Validators.required),
      familyName: new FormControl('' , Validators.required),
      file1: new FormControl('' , Validators.required),
      file2: new FormControl('' , Validators.required),
   });
}

  selectFile(event): void {
    const file = event.target.files[0];
    this.form.patchValue({
      file1: file,
      file2: file
    });
  }

onSubmit(): void {
    const formData: any = new FormData();
    formData.append('name', this.form.get('name').value);
    formData.append('familyName', this.form.get('familyName').value);
    formData.append('file1', this.form.get('file1').value);
    formData.append('file2', this.form.get('file2').value);
    this.uploadService.uploadFiles(formData).subscribe( data => {
          this.successMessage = data.message;
        },
        err => {
          console.log(err);
          this.inputErrorMessage = err.error.error;
          console.log('Errors', this.inputErrorMessage);
          this.errorMessage = err.error.message;
          console.log('Message', this.errorMessage);
        }
    );
  }

uploadService.ts

  uploadFiles(formData): Observable<any> {
    return this.http.post(this.urlResume, formData);
  }

I've already tried some examples like these one but with no success:

Using reactive form validation with <input type="file"> for an Angular app

I have solved my problem by using api

https://www.npmjs.com/package/ngx-material-file-input

for those who are intrested, final solution:

<ngx-mat-file-input formControlName="applicationLetter"
 (change)="selectFile2(form.value)" required></ngx-mat-file-input>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM