7

I have the following line in HTML:

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

Upon selecting a file, the OnFileSelected callback is invoked. But then, if I select the same file again, this callback is not called.

Can you please help?

Zvi Vered
  • 459
  • 2
  • 8
  • 16
  • 2
    That looks like code to be consumed by Angular, not straight HTML. You may want to [edit] your question to update the tags accordingly. – Heretic Monkey Dec 23 '19 at 20:48
  • 1
    Does this answer your question? [How to detect input type=file "change" for the same file?](https://stackoverflow.com/questions/4109276/how-to-detect-input-type-file-change-for-the-same-file) – Aanand Kainth Dec 23 '19 at 20:50

3 Answers3

27

onChange will not detect any change to input type file if the same file has been selected. There are 2 possible ways to make onChange working on same file selection which I would recommend

  1. Either you need to add an event like onClick to clear the value so that the change event will work.

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

  2. Add multiple attribute to the input element

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

Hope this helps.

EDIT:

As suggested by others in comments, you can achieve it like below

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

Anand G
  • 3,130
  • 1
  • 22
  • 28
1

You can also connect to your input element with a element reference and just set it to null when finished.

@ViewChild('fileInput') fileInput: ElementRef;
this.fileInput.nativeElement.value = null;
0

Based on Anand's answer I used the following code:

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

In the ts code:

  public OnFileSelected (event)
  {
    let fileList: FileList = event.target.files;
    this.value = undefined;
  }

Best regards, Zvika

Zvi Vered
  • 459
  • 2
  • 8
  • 16