Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 file input onchange

I have input file (without submit - typicall input file). I'd like to call some function when chose file.

Example: I click on "Choose file" -> choose file -> now system detects change and call some function which prints all these file information (for example image name).

I can't use ngModel on input file, right? How to do that?

like image 938
elzoy Avatar asked Jul 20 '16 08:07

elzoy


3 Answers

Use the following in your template:

<div class="modal-body">
   <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
   <img id="preview" src="" alt="Preview">
</div>

Then your Component fileChangeEvent() as

public fileChangeEvent(fileInput: any){
      if (fileInput.target.files && fileInput.target.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e : any) {
            $('#preview').attr('src', e.target.result);
        }

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

All Your File related info will console....

like image 126
Double H Avatar answered Nov 15 '22 05:11

Double H


Here's my amendments to Double H's answer to not rely on jQuery and stop the webpack erroring out on e.target.result.

<img [src]="imageSrc" alt="" />
<input type="file" capture="camera" accept="image/*" (change)="displayPhoto($event)">

Typescript Code

displayPhoto(fileInput) {
  if (fileInput.target.files && fileInput.target.files[0]) {
  const reader = new FileReader();

  reader.onload = ((e) => {
    this.imageSrc = e.target['result'];
  });

  reader.readAsDataURL(fileInput.target.files[0]);
}

}

like image 7
Kamalpreet Avatar answered Nov 15 '22 05:11

Kamalpreet


Double H's function didn't work for me till I added onclick="this.value = null" as found here: https://stackoverflow.com/a/42357862/634650

like image 5
Chris Avatar answered Nov 15 '22 04:11

Chris