Trần Dương Trần Dương - 5 months ago 45
HTML Question

how to trigger event click at input type="file" by function in angular 2?

I have this code in Html file .

<input #fileInput type="file" />
<button type="button" (click)="triggerFile()">trigger</button>


how can I trigger click event at input type="file" ?
I see this answer : how to trigger click event of input file from button click in angular 2?
Of course it worked . But I want to controll something in triggerFile() function and I don't want to trigger at Html file . I want to trigger input type="file" at my ts File . thanks for help .

Answer

Pass the fileInput reference to triggerFile() and do the fileInput.click() there instead:

<input #fileInput type="file"  />
<button type="button" (click)="triggerFile(fileInput)">trigger</button>
triggerFile(fileInput:Element) {
  // do something
  fileInput.click();
}