dumindu
dumindu

Reputation: 9

preview selected image in angular

I need to preview selected file in angular 6. So I used the following code for that. But there are a few errors. Here's my implementation:

export class AppComponent {
  title = 'imgpreview';

  url = '';
  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event) => { // called once readAsDataURL is completed
        this.url = event.target.result;
      }
    }
  }
}

The error I'm getting:

error is ERROR in src/app/app.component.ts(19,33): error TS2339: Property 'result' does not exist on type 'EventTarget'.

how do I solve this?

Upvotes: 0

Views: 238

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

Specify the type of event as any like this:

reader.onload = (event: any) => { ... }

Give this a try:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'imgpreview';

  url = '';
  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      var reader = new FileReader();

      reader.readAsDataURL(event.target.files[0]); // read file as data url

      reader.onload = (event: any) => { // called once readAsDataURL is completed
        console.log(event);
        this.url = event.target.result;
      }
    }
  }
}

Here's a Working Sample StackBlitz for your ref.

Upvotes: 2

Related Questions