Angular input file: Selecting the same file
Asked Answered
S

4

9

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?

Sigrid answered 23/12, 2019 at 20:44 Comment(3)
That looks like code to be consumed by Angular, not straight HTML. You may want to edit your question to update the tags accordingly.Karyolysis
Does this answer your question? How to detect input type=file "change" for the same file?Rouen
Does this answer your question? HTML input file selection event not firing upon selecting the same fileLentissimo
A
31

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"/>

Abdul answered 23/12, 2019 at 20:58 Comment(2)
(click)="this.value=null" here this.value is not work for me. but (click)="$event.target.value=null" is worked.Tremblay
Thanks @SupunKavinda (click)="$event.target.value=null" this one worked for me alsoSiddra
D
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;
Dettmer answered 28/4, 2022 at 5:45 Comment(0)
G
1

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

please add (click)="fileInput.value = ''"

In 2023 with Angular 16 this works like a charm

Gelatinous answered 11/10, 2023 at 4:3 Comment(0)
S
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

Sigrid answered 24/12, 2019 at 4:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.