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?

2
  • Could you tell us which charting library are you using? Some of the code you tried would be very helpful. Commented Nov 7, 2018 at 7:13
  • @AntonioGarcía yeah its docs.dhtmlx.com/gantt Commented Nov 7, 2018 at 7:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

wouldnt I need a view child to use a nativeElement? I cant add the proper tags to the html to use view child
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.