简体   繁体   English

Angular - 文件输入字段上的更改检测仅工作一次

[英]Angular - Change detection on file input field only works once

The problem is that I have a file input field that takes only one file at a time, I need it to be like this.问题是我有一个文件输入字段,一次只需要一个文件,我需要它是这样的。

If I try to upload one file, everything is fine.如果我尝试上传一个文件,则一切正常。 But if I need to upload more files it seems like the "change" handler method is not being called unless I reload the page, which is not what anyone would want.但是,如果我需要上传更多文件,除非我重新加载页面,否则似乎不会调用“更改”处理程序方法,这不是任何人想要的。

The HTML looks like this: HTML 如下所示:

<div class="col-xs-7">
    <button
      class="btn btn-primary"
      [disabled]="isLoadingModal"
      (click)="activityFileInput.click()">
    archivo</button> {{ newActivity.fileName }}
    <input
      type="file"
      id="activity-file-input"
      [disabled]="isLoadingModal"
      (change)="selectFile(activityFileInput.files[0])"
      #activityFileInput
      hidden>
  </div>

The function in the component is:组件中的功能是:

selectFile(file: File): void {
    console.log('Hello');

    if(file == undefined)
      return;

    this.newActivity.fileName = file.name;
    this.newActivity.file = file;
}

On the first file upload the "Hello" shows, no problem.在第一个文件上传时显示“Hello”,没问题。 But the method doesn't seem to be called more than once.但是该方法似乎不会被多次调用。 How can this be solved?如何解决这个问题?

Set the value of the input to null in the onclick event... 在onclick事件中将输入的值设置为null ...

<input
  type="file"
  id="activity-file-input"
  onclick="this.value = null"
  [disabled]="isLoadingModal"
  (change)="selectFile(activityFileInput.files[0])"
  #activityFileInput
  hidden>

it happens only when you try to upload the same file/image.只有当您尝试上传相同的文件/图像时才会发生这种情况。 When (change) sees the same event, it doesn't trigger the given method.(change)看到相同的事件时,它不会触发给定的方法。 To fix it add (click)="$event.taget.value=null" in your input tag要修复它, (click)="$event.taget.value=null"输入标签中添加(click)="$event.taget.value=null"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM