how to trigger click event of input file from button click in angular 2?

后端 未结 4 1223
一整个雨季
一整个雨季 2021-01-01 08:27



        
相关标签:
4条回答
  • 2021-01-01 09:07

    In Angular 4,

    HTML:

    <input #fileUpload type="file" (click)="fileUpload.value = null"(change)="importFile($event)" style="display:none"
    accept="image/*">
    <button (click)="fileUpload.click()">  </button>
    

    Typescript:

    importFile(event) {
    
    if (event.target.files.length == 0) {
       console.log("No file selected!");
       return
    }
      let file: File = event.target.files[0];
      // after here 'file' can be accessed and used for further process
    }
    

    On considering the future issue of selecting same file not working, In input tag click event we are setting to null, which allows same file to select second time.

    0 讨论(0)
  • 2021-01-01 09:07

    In Angular 4,

    HTML:

    <ion-input type="file" formControlName="avatar"></ion-input>
    <button type="button" ion-button (click)="selectFile()"></button>
    

    Javascript:

    selectFile() {
        let element: HTMLElement = document.querySelector('input[type="file"]') as HTMLElement;
        element.click();
    }
    

    It's work for me.

    0 讨论(0)
  • 2021-01-01 09:13

    You can leverage template reference variable as follows:

    <input type="file" accept="image/*" #file>
    <button (click)="file.click()">Upload file</button>
    

    The corresponding plunkr is here https://plnkr.co/edit/JB4HY0oxEUgXXIht2wAv?p=preview

    0 讨论(0)
  • 2021-01-01 09:32

    You could do have declare variable for input file field as #file & then only file change do call upload function to pass uploaded file to function.

    <input #file type="file" accept="image/*" (change)="upload(file.files)">
    
    <button #upload (click)="file.click()">Upload file</button>
    
    0 讨论(0)
提交回复
热议问题