how to trigger click event of input file from button click in angular 2?
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
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>
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.