简体   繁体   中英

Bind events to dynamically created html in Angular

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM