Rhyeen Rhyeen - 2 years ago 294
Javascript Question

Angular2 - catch/subscribe to (click) event in dynamically added HTML

I'm attempting to inject a string that contains a

event into the Angular2 template. The string is dynamically retrieved from the back-end much after the DOM is loaded. No surprise here that Angular won't recognize the injected

Example template:

<div [innerHTML]="test"></div>

Example string given from back-end:

var test = "When ready, <span (click)=\"itemClick($event)\">click me</span>."

Example function call in the Angular component:

itemClick(event) {

My next guess would be to try having Angular subscribe or catch a plain-old javascript event, so the string would then be:

var test = "When ready, <span onClick=\"itemClick($event)\">click me</span>."

Sure enough, I get an error that
itemClick is not defined
, so I know it's looking for that javascript function.

So question: How can I get Angular2 to subscribe to this event or function?

Answer Source

Declarative event binding is only supported in static HTML in a components template.
If you want to subscribe to events of elements dynamically added, you need to do it imperatively.


or similar.

If you want to be WebWorker-safe, you can inject the Renderer

constructor(private elementRef:ElementRef, private renderer:Renderer) {}

and use instead

this.renderer.listen(this.element.ref.nativeElement, 'click', (event) => { handleClick(e);});

to register an event handler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download