如何在Angular 6中单击图像时打开文件对话框

3

我是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>

如何轻松地打开文件对话框?


你的意思是像这样吗?https://dev59.com/Y1YN5IYBdhLWcg3wHlC3 - לבני מלכה
2个回答

15

这是一个比较旧的问题,但我有一个对于刚刚来到这里的人来说非常简单而且流畅的解决方案。

在你的 <input> HTML 元素中添加一个 ID (在我的例子中是 FileSelectInputDialog)。

<input #FileSelectInputDialog type="file" multiple/>

使用ViewChild在您的组件中创建一个对它的引用:

import { ViewChild } from '@angular/core';

@ViewChild('FileSelectInputDialog') FileSelectInputDialog: ElementRef;

public OpenAddFilesDialog() {
    const e: HTMLElement = this.FileSelectInputDialog.nativeElement;
    e.click();
}

接下来,您可以将(click)="OpenAddFilesDialog()"指令添加到您的图像或任何其他HTML元素中,例如常规按钮:

<button mat-icon-button class="BtnAddFiles" (click)="OpenAddFilesDialog()">
    <mat-icon>add_box</mat-icon>
</button>

1
创建带文件类型的输入,并添加CSS以将其显示为图像。
<div class="boxed">
  <div class="input-group">
      <input id="spFile" class="form-control" name="spFile">
    <input type="file" class="filepicker">
  </div>
</div>

CSS如下:

.filepicker{
    -webkit-appearance: none;
    position:absolute;
    top:1px;
    right:1px;
    width: 40px;
    height: 40px;
    text-indent: 100em;
    background: url('assets/images/maps/Browse.png');
    background-size: cover;
    overflow: hidden;
    cursor: pointer;
    outline: none;
}

还需要添加一个事件发射器来捕获像(change)="onChange($event)"这样的更改事件。


你能否描述一下这个事件发射器部分,因为我是编程新手? - RMD
您可以在此标签中添加事件发射器,以获取用户实际选择的文件并在必要时发送到模态框:<input type="file" class="filepicker" (change)="onChange($event)">。详见https://dev59.com/lVkT5IYBdhLWcg3wh_1U#38476440。 - Prathap Parameswar
尽管它打开了文件浏览器对话框,但它并未显示所附项目。 - RMD
在fileChange事件中,您可以捕获文件名并分配给变量,然后使用Angular模板表达式在另一个div中显示它。https://angular.io/guide/template-syntax - Prathap Parameswar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接