Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger input file click in Ionic 4 after page change

I want to trigger/open a file input coming from another page in Ionic 4.

In page 1 I have a button to go to a modal, in page modal I want to automatically trigger the <input file> dialog

Component

ionViewWillEnter() {
    document.getElementById('file').click(); // Tried with this one 1st, this only works in Internet Explorer / Edge
    this.fileInput.nativeElement.click();    // And also this with @ViewChild
}

HTML

<input type="file" name="file" #file id="file" (change)="fileChange($event)" required>
like image 777
Otto Avatar asked Feb 16 '18 12:02

Otto


3 Answers

This is the code I'm using to trigger a click on an < input>-element:

@ViewChild("file") fileInput: ElementRef;

triggerClick() {
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(this.fileInput.nativeElement, 'dispatchEvent', [event]);
}
like image 91
Frede Avatar answered Oct 21 '22 00:10

Frede


Change this:

ionViewWillEnter() {
    document.getElementById('file').click(); // Tried with this one 1st
    this.fileInput.nativeElement.click();    // And also this with @ViewChild
}

To This:

ionViewDidLoad() {
    document.getElementById('file').click(); // Tried with this one 1st
}
like image 41
Salman Ullah Khan Avatar answered Oct 20 '22 22:10

Salman Ullah Khan


Try ngAfterViewInit() Lifecycle hook that is called after a component's view has been fully initialized.

ngAfterViewInit() {
    document.getElementById('file').click();
}
like image 2
Tony Stark Avatar answered Oct 21 '22 00:10

Tony Stark