简体   繁体   中英

I am not able to read the image. It's showing the following error

This is my ng code:

<div class="p-field col-12">
   <label for="image">Main Image</label>
     <input type="file" class="p-inputtext" accept="image/*" (change)="onImageUpload($event)">
     <div>
       <img {src}="imageDisplay" alt="">
     </div>
</div>

This is my component code:

export class ProductsFormComponent implements OnInit {
     
  imageDisplay: string | ArrayBuffer | null | undefined;
       
  constructor() { }
    
  ngOnInit(): void {}

  onImageUpload(event){
    const file = event.target.files[0];

    if (file) {
      const fileReader = new FileReader();
      
      fileReader.onload = () => {
            this.imageDisplay = fileReader.result;
      }

      fileReader.readAsDataURL(file);
    }
  }    
  }

  get productForm(){
    return this.form.controls;
  }
}

This is the Error:

Error: apps/admin/src/app/pages/products/products-form/products-form.component.ts:77:17 - error TS7006: Parameter 'event' implicitly has an 'any' type.

77   onImageUpload(event)

Use this

const file: File = <File>event.target.files[0];

instead of

this.file = event.target.files[0];

and then

const reader = new FileReader();
reader.readAsDataURL(file);

try this it will work

请尝试onImageUpload(event:any)这应该可以工作。

The error is due to the way you defined the onImageLoad method.

onImageUpload(event)

This is because of typescript.

  1. As angular uses typescript we can specify the type of arguments to method calls. Example: the following will resolve the error
onImageUpload(event: Event)
  1. There is a tsconfig.json file autogenerated by angular cli. This file specifies the config for the typescript compiler to use while compiling your code. Here we can configure the typing we require in the project etc. So setting noImplicitAny option to false will solve the issue too.

I would recommend to go with option1 if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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