codebot
codebot

Reputation: 707

Drop an image in a div and display a preview, using Angular6

I want to drag and drop an image in a div and in the same div, I would like to display a preview of that image.

I have created a simple vanilla JS/HTML5 code that I am now trying to reform to Angular 6 .

This is my code so far

<div id="imageDrop" (drop)="drop($event)" (dragover)="allowDrop($event)" #imageDrop>

@ViewChild('imageDrop') imageDrop; 

  allowDrop(e) {
    e.preventDefault();
  }

  drop(e) {
    e.preventDefault();
    this.checkfiles(e.dataTransfer.files);
  }

  checkfiles(files){    
    if (files.length>1){
      this.imageDrop.innerHTML="Only one image/time";       
      return;
    }   
    else
    {
      this.readfiles(files);
    }
  }

  readfiles(files){
    var reader = new FileReader();
    reader.onload =  (event) =>{
      console.log('readfiles event ===== ',event);
      var image = new Image();
      image.src = event.target.result;
      image.width = 50; 
      this.imageDrop.appendChild(image);
    };
    reader.readAsDataURL(files[0]);
  }

All my issues are in the readfiles.

First, VScode says Property result does not exist on type EventTarget, about the image.src = event.target.result; line. I dont know how to fix this, since this is pretty much what I want to put in the img.src, to later append it. By the way, the console log prints an event , where an image is contained in the event.target.result

Second, even if I try to drop an image there and gets its preview, console says ERROR TypeError: _this.imageDrop.appendChild is not a function.

How can I proceed to get the image I just dropped and preview it in that div ? Thank you

Upvotes: 0

Views: 1291

Answers (1)

user184994
user184994

Reputation: 18301

You should specify that the type of event.target is FileReader, which will the give you access to result.

Also, to get the appendChild function, you first need to access the nativeElement.

The following code should work:

  readfiles(files){
    var reader = new FileReader();
    reader.onload =  (event) =>{
      console.log('readfiles event ===== ',event);
      var image = new Image();
      var fileReader = event.target as FileReader;
      image.src = fileReader.result;
      image.width = 50; 
      this.imageDrop.nativeElement.appendChild(image);
    };
    reader.readAsDataURL(files[0]);
  }

Upvotes: 1

Related Questions