我试图在每次选择文件时触发
onchange
事件。如果我选择的文件不同,它确实会触发,但是,即使选择同一文件两次,我也想触发。
html
<input name="file" type="file" (change)="onChange($event)" style="width:80%" />
组件
onChange(event: any) {
let files = event.srcElement.files;
this.files = files;
event= null;
}
实现这种跨浏览器且无需更改太多代码的最可靠方法是在单击时将输入值设置为 null。
onclick="this.value = null"
所以你的输入看起来像这样
<input name="file" type="file" onclick="this.value = null" (change)="onChange($event)" style="width:80%"/>
这是一个工作示例:plnkr
需要清除文件输入的值。就像您选择与值匹配的文件一样,如果值相同则没有更改事件。
你需要使用JS原生
onclick
<input name="file" type="file" onclick="value = null" (change)="onChange($event)" style="width:80%"/>
如果你使用 Angular 的
(click)
那么它将设置 ts 变量 value
这可能会导致错误,因为它不会在你的 ts 文件中声明。
如果你想使用 angualr 的
(click)
事件,那么使用这样的模板变量
<input name="file" type="file" (click)="myInputFile.value = null" (change)="onChange($event)" style="width:80%" #myInputFile/>
我通过在点击事件上设置 $event.target.value = '' 解决了这个问题
<input type="file" name="file" id="File" aria-label="File" class="file" (click)= "$event.target.value = ''"
(change)="uploadData($event)" accept=".csv, .xlsx">
这对我有用,您现在可以多次上传同一文件。
我通过设置输入元素引用解决了这个问题,即 this.bannerUploader.nativeElement.value = null。
Html:
<input type="file" accept="image/*" hidden #banner (change)="fileChanged($event)" />
<button type="button" (click)="fileUploadClick()"></button>
TypeScript:
@ViewChild('banner') bannerUploader: ElementRef;
fileUploadClick(){
this.bannerUploader.nativeElement.value = null;
this.bannerUploader.nativeElement.click();
}