Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to trigger event click at input type="file" by function in angular 2?

I have this code in Html file .

<input #fileInput type="file"  />

demo.ts

import {
  Component,
  Inject,
  OnInit,
  ElementRef,
  Renderer,
  ViewQuery
} from '@angular/core';
@Component({
  selector: 'demo',
  templateUrl: 'client/dev/demo/demo.html',
})
export class DemoComponent implements OnInit{

@ViewQuery('fileInput') fileInput:ElementRef;

constructor(){}

triggerFile(){
   // do something 
   // trigger input type="file" here
   this.fileInput.nativeElement.click();
}

ngOnInit() {


}

}

I see this answer : how to trigger click event of input file from button click in angular 2? Of course it worked . But I want to trigger input type="file" in triggerFile() function and I use ViewQuery and nativeElement.click() function . but it console this error "Cannot read property 'nativeElement' of undefined" . I use angular2 Rc 1 . thank for help .

like image 463
Trần Dương Avatar asked Jul 08 '16 08:07

Trần Dương


2 Answers

No need to write code in controller

<input #fileInput type="file"  />
<button type="button" (click)="fileInput.click()">trigger</button>
like image 132
Daniel Delgado Avatar answered Oct 21 '22 11:10

Daniel Delgado


Pass the fileInput reference to triggerFile() and do the fileInput.click() there instead:

<input #fileInput type="file"  />
<button type="button" (click)="triggerFile(fileInput)">trigger</button>
triggerFile(fileInput:Element) {
  // do something
  fileInput.click();
}
like image 40
Günter Zöchbauer Avatar answered Oct 21 '22 13:10

Günter Zöchbauer