我按照最新的Angular 11,但仍然const file = (event.target as HTMLInputElement).files[0];
说:对象可能为空
这是OnInit类:
imagePreview : string | any;
form: FormGroup | any;
这是imagepicker函数:
onImagePicked(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
this.form.patchValue({
image: file
});
this.form.get('image').updateValueAndValidity();
const reader = new FileReader();
reader.onload = () => {
this.imagePreview = reader.result as string;
}
reader.readAsDataURL(file);
}
3条答案
按热度按时间ecr0jaav1#
尝试使用if语句检查文件是否存在。
zed5wv102#
只不过HTMLInputElement文件类型如下:文件列表||null,所以我假设File也是null,代码如下所示。
}
hgncfbus3#
这对我很有效:)