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

前端 未结 2 383
眼角桃花
眼角桃花 2020-12-03 12:07

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 t

2条回答
  •  鱼传尺愫
    2020-12-03 13:00

    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

提交回复
热议问题