the programoholic
the programoholic

Reputation: 48

Angular : Dynamic event

want to attach a click event to the dynamically created html element. The click event will should be able to fire another method in component.

I have already gone through other SO answers suggesting to use ElementRef to attach event. But, its not working for my case.

I am using mapQuest API to render map. The map will have geocode plotted & it will add a roll over content. To add the rollover content I am using the API method of mapQuest, like info.setInfoContentHTML('click me');

Just for reference: https://developer.mapquest.com/documentation/javascript-api/pois-infowindows/

The link will be inside the popup which will be added to the dom dynamically by plugin when user hover on the icon. How to add event listener on the link which is shown only when the user hover over & there is no callback event provided by plugin which can fire after hover popup is displayed.

Upvotes: 1

Views: 1777

Answers (1)

Full Stack
Full Stack

Reputation: 36

Angular processes the template when the component is compiled. Any HTML added later is not compiled again and bindings are ignored.

You can use the following :

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  // assume dynamic HTML was added before
  this.elRef.nativeElement.querySelector('button').addEventListener('click', 
  this.onClick.bind(this));
}

your use case :

public createElement(){

  const ele = '<button>click me</button>';
  this.elRef.nativeElement.querySelector('button').addEventListener('click', 
  this.methodName.bind(this));
  info.setInfoContentHTML(ele);
}

public methodName(){

      console.log('event called');
    }

Upvotes: 2

Related Questions