20

I'm using ng2-file-upload (single upload example) and I want to use: ng2FileSelect with a button or a div instead of a file input. How can I do this?

I want this to do something like this:

<button ng2FileSelect [uploader]="uploader">Choose file</button>

Instead of:

<input type="file" ng2FileSelect [uploader]="uploader" />

If does not exist a clean way using ng2-file-upload, do you know an alternative?

1
  • 1
    Do you find a way to achieve this? Commented Feb 13, 2017 at 13:37

3 Answers 3

33

One possible solution is to leverage Angular 2's template variables, and to assign a template variable to the input element; once done, you can directly invoke methods defined on that input from another element, such as a button.

I did the following in one of my applications; it works on IE11, Firefox, and Chrome:

<button (click)="fileInput.click()" class="btn btn-default">Upload</button>
<span style="visibility: hidden; position: absolute; overflow: hidden; width: 0px; height:0px;border:none;margin:0; padding:0">
     <input type="file" #fileInput ng2FileSelect [uploader]="uploader" />
</span>

So as you can see, the button is simply calling the #fileInput's click event within its own click event.

Note that I'm burying the input within a span, and then hiding the span from view via a bunch of styles, such that only the button is visible. Also note that applying these styles to the input element directly seemed to cause problems in IE11.

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

1 Comment

Great idea! Your example was a good model that worked for me. Thank you!
7

Yon can wrap input[file] element with label element and hide it. See this answer and this example

Here's the code.

HTML:

<label for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Custom Upload
</label>
<input id="file-upload" type="file"/>

CSS:

input[type="file"] {
    display: none;
}
.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

Comments

2

In a simple way, you can do it with label, you just have to hide the input.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<label class="btn custom-input-btn">
<input type="file" name="photo" style="display:none" accept="*" multiple>        
<i class="fa fa-cloud-upload"></i> Upload Files
</label>

Comments

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.