I am trying to fire click event (or any other event) on element programatically , In other word I want to know the similar features as offered by jQuery .trigger() method in angular2.
Is there any built in method to do this? ..... if not please suggest how can i do this
Consider the following code fragment
<form [ngFormModel]="imgUploadFrm"
(ngSubmit)="onSubmit(imgUploadFrm)">
<br>
<div class="input-field">
<input type="file" id="imgFile" (click)="onChange($event)" >
</div>
<button id="btnAdd" type="submit" (click)="showImageBrowseDlg()" )>Add Picture</button>
</form>
Here when user click the btnAdd it should fire the click event on imgFile
This worked for me:
and inside the controller:
Angular4
Instead of
use
because
invokeElementMethod
won't be part of the renderer anymore.Angular2
Use ViewChild with a template variable to get a reference to the file input, then use the Renderer to invoke
dispatchEvent
to fire the event:Update
Since direct DOM access isn't discouraged anymore by the Angular team this simpler code can be used as well
See also https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
Günter Zöchbauer's answer is the right one. Just consider adding the following line:
In my case I would get a "caught RangeError: Maximum call stack size exceeded" error if not. (I have a div card firing on click and the input file inside)
If you want to imitate click on the DOM element like this:
and have something like this on the page:
your function in
component.ts
should be like this:I also wanted similar functionality where I have a File Input Control with
display:none
and a Button control where I wanted to trigger click event of File Input Control when I click on the button, below is the code to do soas simple as that and it's working flawlessly...