繁体   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