简体   繁体   English

Object 可能是 null。 TypeScript 错误(角度打字稿)

[英]Object is possibly null. TypeScript error (angular typescript)

I want to add an image file to "convert" function.我想添加一个图像文件来“转换”function。

this is my code from the component.html for the input:这是我的来自 component.html 输入的代码:

<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:该事件假设将 object 的值与所有值 + 图像文件从表单发送到 component.ts,这是它的代码:

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].我收到 object 的错误,可能是 null for (e.target as HTMLInputElement).files[0]。

how can i fix this?..我怎样才能解决这个问题?..

try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM