how to trigger click event of input file from button click in angular 2?

FileFile UploadAngular

File Problem Overview


<input type="file" accept="image/*">

<button>Upload file</button>

How to trigger click event of input type=file from button's click event in Angular 2?

File Solutions


Solution 1 - File

You can leverage template reference variable as follows:

<input type="file" accept="image/*" #file>
<button (click)="file.click()">Upload file</button>

The corresponding plunkr is here https://plnkr.co/edit/JB4HY0oxEUgXXIht2wAv?p=preview

Solution 2 - File

You could do have declare variable for input file field as #file & then only file change do call upload function to pass uploaded file to function.

<input #file type="file" accept="image/*" (change)="upload(file.files)">

<button #upload (click)="file.click()">Upload file</button>

Solution 3 - File

In Angular 4,

HTML:

<ion-input type="file" formControlName="avatar"></ion-input>
<button type="button" ion-button (click)="selectFile()"></button>

Javascript:

selectFile() {
	let element: HTMLElement = document.querySelector('input[type="file"]') as HTMLElement;
	element.click();
}

It's work for me.

Solution 4 - File

In Angular 4,

HTML:

<input #fileUpload type="file" (click)="fileUpload.value = null"(change)="importFile($event)" style="display:none"
accept="image/*">
<button (click)="fileUpload.click()">  </button>

Typescript:

importFile(event) {

if (event.target.files.length == 0) {
   console.log("No file selected!");
   return
}
  let file: File = event.target.files[0];
  // after here 'file' can be accessed and used for further process
}

On considering the future issue of selecting same file not working, In input tag click event we are setting to null, which allows same file to select second time.

Solution 5 - File

You can write something like this if you want to gracefully display the name of the uploaded file.

<div style="display:flex; flex-direction: row;">
  <input type="text" disabled value="{{fileName}}">
  <button (click)="fileInput.click()">File Upload </button>
  <input #fileInput type="file" (change)="onChange($event)" style="display:none"/>
</div>

In your TS file you'll have to make following changes

  fileName: string = "";
  onChange(event) {
    this.fileName = event.target.files[0].name;
  }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamolView Question on Stackoverflow
Solution 1 - FileyurzuiView Answer on Stackoverflow
Solution 2 - FilePankaj ParkarView Answer on Stackoverflow
Solution 3 - FilemaSC0d3RView Answer on Stackoverflow
Solution 4 - FileMani deepView Answer on Stackoverflow
Solution 5 - FileAnurakt GhoshView Answer on Stackoverflow