Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

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

I'm attempting to inject a string that contains a (click) 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 (click) event.

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) {
   debugger;
}


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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

elementRef.nativeElement.querySelector(...).addEventListener(...)

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.elementRef.nativeElement, 'click', (event) => { handleClick(event);});

to register an event handler.

see also Dynamically add event listener in Angular 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...