Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Programmatically Trigger 'Click' Event in Angular 6?

Essentially, I want to trigger the input button in the page using TypeScript

like image 645
RedOne Avatar asked Aug 15 '18 12:08

RedOne


2 Answers

//its no different than doing it in vanilla JS

let elem = document.getElementById('submitBtn');

let evt = new MouseEvent('click', {
        bubbles: true,
        cancelable: true,
        view: window
    });

elem.dispatchEvent(evt);
like image 175
Thomas Lang Avatar answered Sep 19 '22 17:09

Thomas Lang


Use @ViewChild as follows in .ts

 @ViewChild('fileInput') fileInput: ElementRef;

 let inputElement: HTMLElement = this.fileInput.nativeElement as HTMLElement;
 inputElement.click();

In your .html,

 <input #fileInput type="file" ng2FileSelect (onFileSelected)="fileUpload($event)"/>
like image 32
Parinda Rajapaksha Avatar answered Sep 20 '22 17:09

Parinda Rajapaksha