簡體   English   中英

Angular FormGroup驗證輸入文件上傳

[英]Angular FormGroup validation input file upload

我對文件上傳的表單輸入驗證有問題。 當文件上傳為空時,如何驗證 formControle 輸入。 如何在 selectFile 中設置值,以便當文件輸入為空時,將顯示我從服務器響應中獲得的驗證消息。

我從服務器獲得了其他字段名稱和家庭名稱的響應消息,這是因為我在 Html 中使用了 formControlName,這很好用。 但是我不能在文件上傳的輸入字段中使用 formControlName 屬性。

如何在不使用 formControlname 的情況下獲取文件輸入字段的驗證響應消息?

html代碼

 <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代碼

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);
        }
    );
  }

上傳服務.ts

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

我已經嘗試了一些像這樣的例子,但沒有成功:

對 Angular 應用程序使用帶有 <input type="file"> 的反應式表單驗證

我已經通過使用 api 解決了我的問題

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

對於那些有興趣的人,最終解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM