Home > Net >  Unable to programmatically open input selector dialog in Angular
Unable to programmatically open input selector dialog in Angular

Time:02-12

I have an Angular app which has a stylized input box so I keep another actual element which I call .click() on to open the dialog

This used to work great but for some reason stopped working recently? Anyway I can't make it work even though this all should be quite simple to do...

I've tried every way I can think to access my input and click it all to no avail

  <input type="file" id="fileInputRef">
  <button (click)="fileInputRef.click()">open</button>

this produces the error "Cannot read properties of undefined (reading 'click')"

  <input type="file" #fileInputRef>
  <button (click)="fileInputRef.click()">open</button>

this produces no effect at all, no error in console even

so I tried moving it to my component's code like so

  <input type="file" #fileInputRef>
  <button (click)="doClick()">open</button>

and in my typescript

  @ViewChild('fileInputRef') fileInputRef: HTMLInputElement;
  
  public doClick() {
    this.fileInputRef.click();
  }

but then this errors with "this.fileInputRef.click is not a function"

If I print out this.fileInputRef it looks like "ElementRef {nativeElement: input}"

So lastly I tried

  public doClick() {
    this.fileInputRef.nativeElement.click();
  }

which produces no effect

I'm not sure why this feature used to be working and stopped but I'm sure I'm missing something basic

How can I programmatically fire of a click for a file input element in my html

CodePudding user response:

You can use ElementRef to click file type from html. See below code implemented properly and it works fine.

<input type="file" (change)="handleFileInput($event.target.files)" #fileInput style="display:none" multiple>
<button type="button"(click)="fileInput.click()" > Open </button>

@ViewChild('fileInput') myFileInputVariable: ElementRef;

And when you want to reset input field.

this.myFileInputVariable.nativeElement.value = "";

CodePudding user response:

No idea what happened but this was resolved after I updated and restarted Chrome :-\ everything started to work again normally

  • Related