我是 Angular 6 的新手。我知道这可能很愚蠢,但我没有得到任何解决方案。单击文本字段中的浏览图像时,我想打开文件对话框。这是我尝试过的。
<div class="boxed">
<div class="input-group">
<input id="spFile" class="form-control" name="spFile">
<img src="../../../../../assets/images/maps/Browse.png" type= "file" width="40" height="40" style=" position: absolute; top: 1px; right: 1px" aria-hidden="true"/>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我怎样才能让这个轻松打开一个文件对话框?
这是一个相对较旧的问题,但对于刚刚来到这里的人,我有一个简单而流畅的解决方案。
为您的<input>HTML 元素添加一个 ID (FileSelectInputDialog在我的示例中)。
<input #FileSelectInputDialog type="file" multiple/>
Run Code Online (Sandbox Code Playgroud)
使用ViewChild以下命令在您的组件中创建一个句柄:
import { ViewChild } from '@angular/core';
@ViewChild('FileSelectInputDialog') FileSelectInputDialog: ElementRef;
public OpenAddFilesDialog() {
const e: HTMLElement = this.FileSelectInputDialog.nativeElement;
e.click();
}
Run Code Online (Sandbox Code Playgroud)
然后您可以将(click)="OpenAddFilesDialog()"指令添加到您的图像或任何其他 HTML 元素,例如,添加到常规按钮:
<button mat-icon-button class="BtnAddFiles" (click)="OpenAddFilesDialog()">
<mat-icon>add_box</mat-icon>
</button>
Run Code Online (Sandbox Code Playgroud)