0

In my angular (6) app I am using a charting library that generates the chart and its html after the component is initialized.

I would like to add events (specifically a hover event) when hovering over a certain div. I would normally just use the built in angular (mouseover) but since the html is generated by the library, I don't have access to the html to add these things.

How can I add these events after the html is generated?

halfer
  • 19,824
  • 17
  • 99
  • 186
cup_of
  • 6,397
  • 9
  • 47
  • 94

1 Answers1

3

Since you don't have access to the dynamically generated HTML the choices you have are two:

  1. Fork the library's code and add the event listener. Then use the forked code in your application. I would advise strongly against this tho. You would need to maintain another library and this can lead to a lot of errors and a lot of overhead
  2. Add an event listener directly to the generated HTML element. This would be a more direct solution without much overhead.

So expanding on 2.:

You would need to use listen from Renderer2 from angular, which is detailed in docs here and in this answer as well. In sort you need to create something like this:

let global = this.renderer.listen('document', 'click', (evt) => {
  console.log('Clicking the document', evt);
})

let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
  console.log('Clicking the button', evt);
});

Please also keep in mind that the element should already be rendered for this to work, so you need to place this code either inside the ngAfterViewInit() lifecycle hook or set a timeout (not advised - you don't want to have to debug race conditions as well).

As a note, please also see the plunker of the linked issue to see the full implementation.

  • wouldnt I need a view child to use a nativeElement? I cant add the proper tags to the html to use view child – cup_of Nov 07 '18 at 08:38
  • 1
    Yes, something in the lines of "@ViewChild('myButton') myButton;" if you check the plunker attached in the linked issue it shows how it can be done. – Giannis Smirnios Nov 08 '18 at 11:41