Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use ng2-file-upload with button instead of a file input?

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?

like image 235
Leantraxxx Avatar asked Aug 24 '16 20:08

Leantraxxx


3 Answers

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.

like image 113
RMD Avatar answered Nov 18 '22 19:11

RMD


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;
}
like image 36
Roman Kondakov Avatar answered Nov 18 '22 19:11

Roman Kondakov


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>
like image 2
Adel Faidi Avatar answered Nov 18 '22 18:11

Adel Faidi