How to bind event listener for rendered elements in Angular 2?

Sudhanshu sharma picture Sudhanshu sharma · Jan 12, 2017 · Viewed 124.6k times · Source

How can I bind an event listener in rendered elements in Angular 2?

I am using Dragula drag and drop library. It creates dynamic HTML but my event is not bound to dynamic HTML elements.

Answer

Günter Zöchbauer picture Günter Zöchbauer · Jan 12, 2017
import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

onClick(event) {
  console.log(event);
}