0

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?..

1
  • 1
    I don't use typescript, but probably you need to check e.target as HTMLInputElement != null or e.target is HTMLInputElement first. before access .files Commented Jan 5, 2021 at 14:44

1 Answer 1

7

try this:

this.eventFiles = (e.target as HTMLInputElement)?.files?.[0];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.