1

I've a simple input of type file and I need to check a boolean variable before opening the file dialog to choose a file. Is there a way to do this? This is my code:

<input type="file" id="uploadFile" [disabled]="disableUpload" (change)="onUpload($event)" />

Clicking on input, a file dialog is shown. I need to do a check that, if positive, block the file dialog opening. Thanks to everybody!

bigskull
  • 541
  • 2
  • 18
  • 28

1 Answers1

4

You might try adding attr.disabled instead of disabled

<input [attr.disabled]="disableUpload ? '' : null"/>

Or if you are using reactive forms (I suggest you to do so), you may disable it using the form control.

UPDATE

You can assign a method to click event on file input and then check for the boolean value to perform desired operation.

In the component:

fileDialogShouldOpen = false;

fileInputClick = (event) => {

    // Open file dialog
    if(this.fileDialogShouldOpen){
      return true;
    }
    // Do not open file dialog
    else{

      event.preventDefault();
      event.stopPropagation();
      return false;
    }
}

And in the template:

<input type="file" (click)="fileInputClick($event)">

You can find a working example in this stackblitz project

Harun Yilmaz
  • 8,281
  • 3
  • 24
  • 35
  • And also see: [https://stackoverflow.com/questions/42179150/how-to-disable-a-input-in-angular2/43765804](https://stackoverflow.com/questions/42179150/how-to-disable-a-input-in-angular2/43765804) – Harun Yilmaz Jan 28 '19 at 14:50
  • I don't want to disable the input, I just want to do something (checking a boolean) before opening the file dialog to choose a file. If check result false I don't want to open the file dialog. – bigskull Jan 28 '19 at 15:36
  • @bigskull Glad to help :) – Harun Yilmaz Jan 29 '19 at 11:09
  • @bigskull Btw, instead of editing the title as "solved", you may mark the working answer as accepted. Please see: [https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question](https://meta.stackexchange.com/questions/116101/is-it-ok-to-add-solved-to-the-title-of-a-question) – Harun Yilmaz Jan 29 '19 at 11:12
  • The update works perfectly. Thx! – AdamWist Mar 14 '22 at 11:59