Reputation: 35
I want to add an image file to "convert" function.
this is my code from the component.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 component.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?..
Upvotes: 0
Views: 3297
Reputation: 3823
try this:
this.eventFiles = (e.target as HTMLInputElement)?.files?.[0];
Upvotes: 7