首页 > 解决方案 > Angular - 清除文件输入

问题描述

我有一个组件,允许用户填写一些字段以及选择个人资料图片。提交表单后,我正在尝试清除它,以便他们可以添加另一个条目。

组件 HTML:

<input type="file" #userPhoto name="userPhoto" id="userPhoto" (change)="onFileChange($event)" />

组件 TS:

@ViewChild('userPhoto') userPhoto: any;

...

private prepareSave(value): any {
 const Image = this.userPhoto.nativeElement;
 if (Image.files && Image.files[0]) {
   this.userPhoto = Image.files[0];
 }
 const ImageFile: File = this.userPhoto;
 const formData: FormData = new FormData();
 formData.append('ParentUserID', value.parentUserID);
 formData.append('FirstName', value.firstName);
 formData.append('LastName', value.lastName);
 formData.append('Age', value.age);
 formData.append('Photo', ImageFile, ImageFile.name);
 return formData;
}

...

<Submit Form>
clearSelectedPhoto() {
  this.userPhoto.nativeElement.value = null;
}

现在,我认为问题在于我viewChild正在使用any而不是ElementRef. 但是,当我更改此设置时,打字稿会在方法中抱怨我的行prepareSave

const ImageFile: File = this.userPhoto;

[ts] 类型“ElementRef”不可分配给类型“文件”。“ElementRef”类型中缺少属性“lastModified”。

我如何使用ElementRefviewChild的照片以及File稍后分配照片?

我试图在我的重置方法中投射它,但看起来也不起作用。

   clearSelectedPhoto() {
     (<ElementRef>this.userPhoto).nativeElement.value = null;
    }

抛出:错误错误:未捕获(承诺):TypeError:无法设置未定义的属性“值”

标签: angulartypescript

解决方案


您必须从更改事件中获取文件。

组件 HTML:

<input #userPhoto type="file" (change)="fileChange($event)"/>

组件 TS:

@ViewChild('userPhoto') userPhoto: ElementRef;
private _file: File;

private prepareSave(value): FormData {
    const formData: FormData = new FormData();
    formData.append('ParentUserID', value.parentUserID);
    formData.append('FirstName', value.firstName);
    formData.append('LastName', value.lastName);
    formData.append('Age', value.age);
    formData.append('Photo', this.file, this.file.name);
    return formData;
}


fileChange(event) {
    this.file = event.srcElement.files[0];
}
clearSelectedPhoto() {
    this.userPhoto.nativeElement.value = null;
}

当您使用 TS be shure 在任何地方声明类型时,它可以避免很多错误。不要any从函数返回。即使您的函数在函数声明 ex: 中返回多个类型指向它getFile(): File | string

不要像这样使用相同的变量:

@ViewChild('userPhoto') userPhoto: any;
...
    if (Image.files && Image.files[0]) {
       this.userPhoto = Image.files[0];
    }

在您的代码中,您用文件覆盖了指向输入元素的指针,然后当您尝试清除它的值时,您实际上this.userPhoto.nativeElement.value = null;写入了Image.files[0].value = null;.


推荐阅读