using input type file with angular material 2

Viewed 42507

How can I use angular material 2 FAB buttons to open a browse input dialog? This can be done in HTML by this way.

<button type="button">
    <label for="file-input">click</label>
</button>
<input type="file" id="file-input" style="display:none">

I tried following 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 will work? Thank you.

6 Answers

Try this:

<input #file type="file" [hidden]="true" accept="image/*" (change)="upload(file.files)">
<button mat-button #upload (click)="file.click()">Upload file</button>

<mat-button> is from https://material.angular.io

We are hiding the basic input button and linking the material button to the file upload.

You can use a button and an input. Make sure that button doesn't enclose input.

<button (click)="fileInput.click()">Upload</button>
<input #fileInput type="file" (change)="onFileInput($event)" multiple style="display:none;" />

You can also use a label enclosing an input.

<label>
    <mat-icon>add</mat-icon>
    <input type="file" (change)="onFileInput($event)" multiple />
</label>
Related