使用带角度材料的输入类型文件2

Sai*_*aif 12 angular-material2 angular

如何使用角度材料2 FAB按钮打开浏览输入对话框?这可以通过这种方式在HTML中完成.

<button type="button">
    <label for="file-input">click</label>
</button>
<input type="file" id="file-input" style="display:none">
Run Code Online (Sandbox Code Playgroud)

我尝试使用与材料2相同的方法,但它不起作用.

<button md-mini-fab type="button">
    <label for="fileToUpload">
        <md-icon>add</md-icon>
    </label>
</button>
<input id="fileToUpload" type="file" style="display:none;">
Run Code Online (Sandbox Code Playgroud)

还有其他方法可行吗?谢谢.

小智 48

这是一个简单的解决方案:

<button (click)="fileInput.click()">
  <md-icon>library_add</md-icon>
  <span>Select</span>
  <input #fileInput type="file" (change)="onFileInput($event)" style="display:none;" />
</button>
Run Code Online (Sandbox Code Playgroud)


ano*_*oop 15

您只需触发click文件输入即可.

<button md-mini-fab type="button" onclick="document.getElementById('fileToUpload').click()">
  <label for="fileToUpload"><md-icon>add</md-icon></label>
</button>
<input id="fileToUpload" type="file" style="display:none;">
Run Code Online (Sandbox Code Playgroud)


Ash*_*n R 11

试试这个:

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

<mat-button>来自https://material.angular.io

我们隐藏了基本输入按钮并将材质按钮链接到文件上传.


小智 7

家伙.我不确定你的情况,但在我的Angular5应用程序中,我使用下一个HTML结构在服务器上上传文件:

<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])">
Run Code Online (Sandbox Code Playgroud)

就我而言,这个解决方案运行良好.无需触发click事件,因为当您点击<label>与之相关的事件时,input就像click开启事件一样input.