Angular 输入文件:选择相同的文件

Zvi*_*red 3 html file input

我在 HTML 中有以下行:

<input type="file" #fileInput style="display: none"  accept=".xml" (change)="OnFileSelected($event)"/>
Run Code Online (Sandbox Code Playgroud)

选择文件后,将调用 OnFileSelected 回调。但是,如果我再次选择同一个文件,则不会调用此回调。

你能帮忙吗?

Ana*_*d G 8

onChange如果选择了相同的文件,则不会检测对输入类型文件的任何更改。有 2 种可能的方法来onChange处理我推荐的相同文件选择

  1. 您需要添加一个事件onClick来清除该值,以便更改事件起作用。

    <input type="file" #fileInput style="display: none" accept=".xml" (change)="OnFileSelected($event)" (click)="this.value=null"/>

  2. multiple给 input 元素添加属性

<input type="file" #fileInput style="display: none" accept=".xml" (change)="OnFileSelected($event)" multiple/>

希望这可以帮助。

编辑:

正如其他人在评论中所建议的那样,您可以像下面那样实现

<input type="file" #fileInput style="display: none" accept=".xml" (change)="OnFileSelected($event)" (click)="$event.target.value=null"/>

  • (click)="this.value=null" 这里 this.value 对我不起作用。但 (click)="$event.target.value=null" 有效。 (4认同)