最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object is possibly null. TypeScript error (angular typescript) - Stack Overflow

programmeradmin1浏览0评论

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 or e.target is HTMLInputElement first. before access .files – apple apple Commented Jan 5, 2021 at 14:44
Add a ment  | 

1 Answer 1

Reset to default 7

try this:

this.eventFiles = (e.target as HTMLInputElement)?.files?.[0];
发布评论

评论列表(0)

  1. 暂无评论