7

I'm trying to make an upload button because I don't want to use the HTML upload button, how can I call a click event on the input element to open the file browser manually?

<div class="upload-button button" (click)="selectFile()">
   Upload
   <input type="file">
</div>
1

2 Answers 2

5

I would do it with the # decorator in the view. This way we can give the input a name and just call name.click() to call it from a button for example:

<button (click)="fileSelect.click()">Click me for fun!</button>
<input style="display: none" #fileSelect type="file">

The # according to docs: "Creates a local variable that provides access to the element instance in data-binding and event-binding expressions in the current template." Cheatsheet

Sign up to request clarification or add additional context in comments.

Comments

3

Just click will make it work as per my understanding:

<div class="upload-button button" (click)="file.click()">
  Upload
  <input type="file" #file>
</div>

Hope it helps!

5 Comments

No, if you click on the text Upload it will not open the file chooser. click="file" means nothing.
@LajosArpad , Thanks for your comment. I have updated the code snippet as per my understanding.
This is still not correct. file does not mean anything in that context. You will just need to find the input, possibly by id, see my answer.
@LajosArpad, okay. Thanks again.
@stol has explained it correctly in the answer above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.