I want to add an image file to "convert" function.
this is my code from the ponent.html for the input:
<li>
<label for="avatarIMG" id="avatarLbL"> image: </label>
<input type="file" accept="image/*" #imageBox name="image" id="avatarinput" (change)="convert($event)">
<button type="button" id="avatarInputBTN" (click)="imageBox.click()"> Profile Picture </button>
</li>
the event suppose to send the values of the object with all of the values + the image file from the form to the ponent.ts and this is the code of it:
public convert(e: Event): void {
this.eventFiles = (e.target as HTMLInputElement).files[0];
if (this.eventFiles !== null) {
this.user.image = this.eventFiles;
const fileReader = new FileReader();
fileReader.onload = args => this.preview = args.target?.result?.toString();
fileReader.readAsDataURL(this.eventFiles);
}
}
i get an error of object possibly null for (e.target as HTMLInputElement).files[0].
how can i fix this?..
I want to add an image file to "convert" function.
this is my code from the ponent.html for the input:
<li>
<label for="avatarIMG" id="avatarLbL"> image: </label>
<input type="file" accept="image/*" #imageBox name="image" id="avatarinput" (change)="convert($event)">
<button type="button" id="avatarInputBTN" (click)="imageBox.click()"> Profile Picture </button>
</li>
the event suppose to send the values of the object with all of the values + the image file from the form to the ponent.ts and this is the code of it:
public convert(e: Event): void {
this.eventFiles = (e.target as HTMLInputElement).files[0];
if (this.eventFiles !== null) {
this.user.image = this.eventFiles;
const fileReader = new FileReader();
fileReader.onload = args => this.preview = args.target?.result?.toString();
fileReader.readAsDataURL(this.eventFiles);
}
}
i get an error of object possibly null for (e.target as HTMLInputElement).files[0].
how can i fix this?..
Share Improve this question edited Jan 5, 2021 at 18:22 Tyler2P 2,37030 gold badges25 silver badges33 bronze badges asked Jan 5, 2021 at 14:39 Michael SodovskiMichael Sodovski 352 silver badges8 bronze badges 1-
1
I don't use typescript, but probably you need to check
e.target as HTMLInputElement != null
ore.target is HTMLInputElement
first. before access.files
– apple apple Commented Jan 5, 2021 at 14:44
1 Answer
Reset to default 7try this:
this.eventFiles = (e.target as HTMLInputElement)?.files?.[0];