I have a component that allows a user to fill out some fields as well as choose a profile picture. After submitting the form, I am trying to clear it so they could add another entry.
Component HTML:
<input type="file" #userPhoto name="userPhoto" id="userPhoto" (change)="onFileChange($event)" />
Component 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;
}
Now, I think the issue is that my viewChild is using any instead of ElementRef. However, when I change this, typescript complains about my line in the prepareSave method:
const ImageFile: File = this.userPhoto;
[ts] Type 'ElementRef' is not assignable to type 'File'. Property 'lastModified' is missing in type 'ElementRef'.
How can I use ElementRef for my viewChild as well as assigning the photo to File later on?
I tried to cast it in my reset method but doesn't look like thats working either.
clearSelectedPhoto() {
(<ElementRef>this.userPhoto).nativeElement.value = null;
}
Throws: ERROR Error: Uncaught (in promise): TypeError: Cannot set property 'value' of undefined