Home > Enterprise >  how can i trigger OnChangeFile input without Button Click in Angular?
how can i trigger OnChangeFile input without Button Click in Angular?

Time:12-03

I am trying to upload files to AWS but I don't want to press the "choose file" button. it should automatically trigger is there any way to achieve this

in my .html file

<div >
  <input (change)="onChangeFile($event)" type="file" />
</div>

in my .ts file

 async onChangeFile(event: any) {
    console.log(event.target.files[0]);
    this.fileSelected = event.target.files[0];
    console.log(environment);
    console.log('Uploaded');
    await this.S3CustomClient.uploadFile(
     .uploadFile(this.fileSelected, this.fileSelected.type, undefined, this.fileSelected.name, "private")
      .then((data: UploadResponse) => console.log(data))
      .catch((err: any) => console.error(err))

CodePudding user response:

For security reasons a file chooser dialog can only be shown with a user activation - so for example click event. What you want is not possible.

CodePudding user response:

You can use dispatchEvent :

<div  >
  <input #fileOne (change)="onChangeFile($event)" type="file" />
</div>

 
//In your TS FILE

@ViewChild("fileOne") fileOne : ElementRef;   

ngAfterViewInit() {
   setTimeout(() => {
   const e = new Event("change");
   this.fileOne.nativeElement.dispatchEvent(e);
  },2000)
}
  • Related