Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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. But the method doesn't seem to be called more than once. How can this be solved?

like image 441
Fer Vargas Avatar asked Mar 20 '18 00:03

Fer Vargas


People also ask

How can you tell if a file is canceled and clicked on input?

The property value type=”file” tells that the type of input the user enters is a file. The property value id=”theFile” is used to link the JavaScript code to it using getElementById() method. The property value onclick=”initialize()” is used to specify the function call when the user has clicked on the input.

How do you identify changes in angular components?

To run the change detector manually: Inject ChangeDetectorRef service in the component. Use markForCheck in the subscription method to instruct Angular to check the component the next time change detectors run. On the ngOnDestroy() life cycle hook, unsubscribe from the observable.

What is NGF select?

ngf-select is a file upload directive which defines what happens when you select the file.


1 Answers

Set the value of the input to null in the onclick event...

<input
  type="file"
  id="activity-file-input"
  onclick="this.value = null"
  [disabled]="isLoadingModal"
  (change)="selectFile(activityFileInput.files[0])"
  #activityFileInput
  hidden>
like image 75
jonhid Avatar answered Sep 19 '22 01:09

jonhid