1

I want to generate click event from within component on some condition. In AngularJs, I used to do:

angular.element(document.querySelector('#someid')).click();

In Angular 2/4/5, I found ElementRef which is not recommended. They say, use renderer, but found no such example to generate click event.

How can do this in Angular 2/4/5?

Ashutosh
  • 4,371
  • 10
  • 59
  • 105
  • I'd advise to not do this but rather call the event handler that click would call on a click. If you have a need to trigger from the element due to other plugins try calling the plug-in events that would happen on click. Like dropdown.expand() etc – Brandon Culley Mar 01 '18 at 03:51
  • Possible duplicate of [angular2 manually firing click event on particular element](https://stackoverflow.com/questions/36639486/angular2-manually-firing-click-event-on-particular-element) – Milad Mar 01 '18 at 04:10

1 Answers1

0

You can use the renderer2 listen method. This can be done with the following line:

constructor(el: ElementRef, renderer: Renderer2) {
    renderer.listen(el.nativeElement, 'click', event => console.log(event));
  }

https://angular.io/api/core/Renderer2

If you need to get an exact element within the template file you can create a reference using #someid

Then in the .ts file use:

 @ViewChild('someid) someid: ElementRef

Then use it once again with the renderer2 passing someid.nativeElement

Hope this helps!

Another alternative is to use: https://angular.io/api/core/HostListener

Jmsdb
  • 515
  • 3
  • 9