DEV Community

Discussion on: How to Programmatically Trigger 'Click' Event in Angular 4 & 5

Collapse
 
reegodev profile image
Matteo Rigon • Edited

Two things I'd like to point out:

  1. You should always use a button instead of a link if you just need to trigger an action
  2. Instead of the openFileBrowser method which is a more "jQuerish" approach you can do that in the angular way with template ref:
<input id="tenantPhotoID" type="file" #photoInput >
<button type="button" (click)="photoInput.click()"  > 

Enter fullscreen mode Exit fullscreen mode
Collapse
 
gloriamaris profile image
Monique Dingding

Hi, Matteo! I am not - by any means - an expert in Angular but I just want to help other developers who may be lost right now looking for solutions by sharing mine. :-) Thanks for these pointers!

Collapse
 
jamesbcn profile image
jamesbcn

This was exactly what I was looking for! Much appreciated.

Thread Thread
 
oif01 profile image
Óscar

Same over here... :)

Collapse
 
viktorkukurba profile image
Viktor

In this case you've missed $event.stopPropagation(), which could be important in some cases.
So, method still can make sense in this case if you'd like to keep your html clean.

Collapse
 
hoyvicente profile image
nate nate

Mine resulted to 'ERROR TypeError: Cannot read property 'click' of undefined'. Did I missed out something?

Collapse
 
reegodev profile image
Matteo Rigon

Hello, sadly i switched to Vue a long time ago so i may be a bit behind current Angular, but if you get that error it appears that you forgot to add to the input the reference attribute #photoInput.

Just tested it here and the code appears to be working as originally wrote:
stackblitz.com/edit/angular-playgr... ( checkout hello-framework/hello-framework.component.html )

Collapse
 
pellanokeith07 profile image
ERROR 401

Hi matteo may I ask if this will work when you use #templateRef using material UI in angular?