Using input type file with angular material 2
How can I use angular material 2 FAB button to open the browse input dialog? It can be done in HTML this way.
<button type="button">
<label for="file-input">click</label>
</button>
<input type="file" id="file-input" style="display:none">
I tried the same approach with material 2, but it doesn't work.
<button md-mini-fab type="button">
<label for="fileToUpload">
<md-icon>add</md-icon>
</label>
</button>
<input id="fileToUpload" type="file" style="display:none;">
Are there any other ways that would work? Thank.
source to share
Try it:
<input #file type="file" [hidden]="true" accept="image/*" (change)="upload(file.files)">
<button mat-button #upload (click)="file.click()">Upload file</button>
<mat-button>
from https://material.angular.io
We hide the main input button and bind the material button to the file upload.
source to share
I'm not sure about your cases, but in my Angular5 app I used this HTML structure to upload files to the server:
<label for="uploadPicture" class="upload-file">
<mat-icon>add_a_photo</mat-icon>
</label>
<input type="file"
id="uploadPicture"
class="hidden-input"
accept="image/jpeg, .jpeg, image/png, .png, image/pjpeg, .jpg"
(change)="selectFile($event.target.files[0])">
This solution works fine in my case. No need to trigger the event click
because when you click on <label>
which is associated with input
it is similar click
to input
.
source to share
It can be a combination of md-button, md-dialog and md-input. The mini fab button must have a click event to trigger the md-dialog component.
<button md-mini-fab type="button" (click)="openDialog()">
<label for="fileToUpload">
<md-icon>add</md-icon>
</label>
</button>
Inside the md-dialog component, you can add an md-input field.
<h1 md-dialog-title>Dialog</h1>
<div md-dialog-actions>
<md-input-container>
<input mdInput id="fileToUpload" type="file">
</md-input-container>
<p>
<button md-button (click)="dialogRef.close('Option 1')">Option 1</button>
<button md-button (click)="dialogRef.close('Option 2')">Option 2</button>
</p>
</div>
Please check out this Plunker for all / specific details.
source to share
You can use the button and enter. Make sure this button does not cover the input .
<button (click)="fileInput.click()">Upload</button>
<input #fileInput type="file" (change)="onFileInput($event)" multiple style="display:none;" />
You can also use a label containing the input.
<label>
<mat-icon>add</mat-icon>
<input type="file" (change)="onFileInput($event)" multiple />
</label>
source to share